From 813e3ffc15442a8199b04671d08b132efe0a55cf Mon Sep 17 00:00:00 2001 From: Ryan McKinley Date: Fri, 10 May 2019 22:41:32 -0700 Subject: [PATCH 001/166] GraphPanel: show results for all SeriesData (#16966) * Graph panel should support SeriesData * Graph panel should support SeriesData * same path for all series * merge master * support docs * add test for processor * Graph: removed old unused data processing logic * Graph: minor refactoring data processing * fix histogram * set Count as title --- public/app/plugins/panel/graph/axes_editor.ts | 11 +- .../app/plugins/panel/graph/data_processor.ts | 189 +++++--------- public/app/plugins/panel/graph/module.ts | 9 +- .../__snapshots__/data_processor.test.ts.snap | 233 ++++++++++++++++++ .../panel/graph/specs/data_processor.test.ts | 86 ++++--- 5 files changed, 346 insertions(+), 182 deletions(-) create mode 100644 public/app/plugins/panel/graph/specs/__snapshots__/data_processor.test.ts.snap diff --git a/public/app/plugins/panel/graph/axes_editor.ts b/public/app/plugins/panel/graph/axes_editor.ts index 04ef62f16fbb..2cb7aa4eed0a 100644 --- a/public/app/plugins/panel/graph/axes_editor.ts +++ b/public/app/plugins/panel/graph/axes_editor.ts @@ -10,7 +10,7 @@ export class AxesEditorCtrl { xNameSegment: any; /** @ngInject */ - constructor(private $scope, private $q) { + constructor(private $scope) { this.panelCtrl = $scope.ctrl; this.panel = this.panelCtrl.panel; this.$scope.ctrl = this; @@ -65,15 +65,6 @@ export class AxesEditorCtrl { xAxisValueChanged() { this.panelCtrl.onDataReceived(this.panelCtrl.dataList); } - - getDataFieldNames(onlyNumbers) { - const props = this.panelCtrl.processor.getDataFieldNames(this.panelCtrl.dataList, onlyNumbers); - const items = props.map(prop => { - return { text: prop, value: prop }; - }); - - return this.$q.when(items); - } } /** @ngInject */ diff --git a/public/app/plugins/panel/graph/data_processor.ts b/public/app/plugins/panel/graph/data_processor.ts index 4b57934824cc..37fe9f3e2195 100644 --- a/public/app/plugins/panel/graph/data_processor.ts +++ b/public/app/plugins/panel/graph/data_processor.ts @@ -1,11 +1,10 @@ import _ from 'lodash'; -import { colors, getColorFromHexRgbOrName } from '@grafana/ui'; +import { TimeRange, colors, getColorFromHexRgbOrName, FieldCache, FieldType, Field, SeriesData } from '@grafana/ui'; import TimeSeries from 'app/core/time_series2'; import config from 'app/core/config'; -import { LegacyResponseData, TimeRange } from '@grafana/ui'; type Options = { - dataList: LegacyResponseData[]; + dataList: SeriesData[]; range?: TimeRange; }; @@ -13,68 +12,81 @@ export class DataProcessor { constructor(private panel) {} getSeriesList(options: Options): TimeSeries[] { - if (!options.dataList || options.dataList.length === 0) { - return []; - } + const list: TimeSeries[] = []; + const { dataList, range } = options; - // auto detect xaxis mode - let firstItem; - if (options.dataList && options.dataList.length > 0) { - firstItem = options.dataList[0]; - const autoDetectMode = this.getAutoDetectXAxisMode(firstItem); - if (this.panel.xaxis.mode !== autoDetectMode) { - this.panel.xaxis.mode = autoDetectMode; - this.setPanelDefaultsForNewXAxisMode(); - } + if (!dataList || !dataList.length) { + return list; } - switch (this.panel.xaxis.mode) { - case 'series': - case 'time': { - return options.dataList.map((item, index) => { - return this.timeSeriesHandler(item, index, options); - }); + for (const series of dataList) { + const { fields } = series; + const cache = new FieldCache(fields); + const time = cache.getFirstFieldOfType(FieldType.time); + + if (!time) { + continue; } - case 'histogram': { - let histogramDataList; - if (this.panel.stack) { - histogramDataList = options.dataList; - } else { - histogramDataList = [ - { - target: 'count', - datapoints: _.concat([], _.flatten(_.map(options.dataList, 'datapoints'))), - }, - ]; + + const seriesName = series.name ? series.name : series.refId; + + for (let i = 0; i < fields.length; i++) { + if (fields[i].type !== FieldType.number) { + continue; } - return histogramDataList.map((item, index) => { - return this.timeSeriesHandler(item, index, options); - }); - } - case 'field': { - return this.customHandler(firstItem); + + const field = fields[i]; + let name = field.title; + + if (!field.title) { + name = field.name; + } + + if (seriesName && dataList.length > 0 && name !== seriesName) { + name = seriesName + ' ' + name; + } + + const datapoints = []; + for (const row of series.rows) { + datapoints.push([row[i], row[time.index]]); + } + + list.push(this.toTimeSeries(field, name, datapoints, list.length, range)); } } - return []; + // Merge all the rows if we want to show a histogram + if (this.panel.xaxis.mode === 'histogram' && !this.panel.stack && list.length > 1) { + const first = list[0]; + first.alias = first.aliasEscaped = 'Count'; + for (let i = 1; i < list.length; i++) { + first.datapoints = first.datapoints.concat(list[i].datapoints); + } + return [first]; + } + return list; } - getAutoDetectXAxisMode(firstItem) { - switch (firstItem.type) { - case 'docs': - return 'field'; - case 'table': - return 'field'; - default: { - if (this.panel.xaxis.mode === 'series') { - return 'series'; - } - if (this.panel.xaxis.mode === 'histogram') { - return 'histogram'; - } - return 'time'; + private toTimeSeries(field: Field, alias: string, datapoints: any[][], index: number, range?: TimeRange) { + const colorIndex = index % colors.length; + const color = this.panel.aliasColors[alias] || colors[colorIndex]; + + const series = new TimeSeries({ + datapoints: datapoints || [], + alias: alias, + color: getColorFromHexRgbOrName(color, config.theme.type), + unit: field.unit, + }); + + if (datapoints && datapoints.length > 0 && range) { + const last = datapoints[datapoints.length - 1][1]; + const from = range.from; + + if (last - from.valueOf() < -10000) { + series.isOutsideRange = true; } } + return series; } setPanelDefaultsForNewXAxisMode() { @@ -110,43 +122,6 @@ export class DataProcessor { } } - timeSeriesHandler(seriesData: LegacyResponseData, index: number, options: Options) { - const datapoints = seriesData.datapoints || []; - const alias = seriesData.target; - - const colorIndex = index % colors.length; - - const color = this.panel.aliasColors[alias] || colors[colorIndex]; - - const series = new TimeSeries({ - datapoints: datapoints, - alias: alias, - color: getColorFromHexRgbOrName(color, config.theme.type), - unit: seriesData.unit, - }); - - if (datapoints && datapoints.length > 0) { - const last = datapoints[datapoints.length - 1][1]; - const from = options.range.from; - - if (last - from.valueOf() < -10000) { - series.isOutsideRange = true; - } - } - - return series; - } - - customHandler(dataItem) { - const nameField = this.panel.xaxis.name; - if (!nameField) { - throw { - message: 'No field name specified to use for x-axis, check your axes settings', - }; - } - return []; - } - validateXAxisSeriesValue() { switch (this.panel.xaxis.mode) { case 'series': { @@ -165,40 +140,6 @@ export class DataProcessor { } } - getDataFieldNames(dataList, onlyNumbers) { - if (dataList.length === 0) { - return []; - } - - const fields = []; - const firstItem = dataList[0]; - const fieldParts = []; - - function getPropertiesRecursive(obj) { - _.forEach(obj, (value, key) => { - if (_.isObject(value)) { - fieldParts.push(key); - getPropertiesRecursive(value); - } else { - if (!onlyNumbers || _.isNumber(value)) { - const field = fieldParts.concat(key).join('.'); - fields.push(field); - } - } - }); - fieldParts.pop(); - } - - if (firstItem.type === 'docs') { - if (firstItem.datapoints.length === 0) { - return []; - } - getPropertiesRecursive(firstItem.datapoints[0]); - } - - return fields; - } - getXAxisValueOptions(options) { switch (this.panel.xaxis.mode) { case 'series': { diff --git a/public/app/plugins/panel/graph/module.ts b/public/app/plugins/panel/graph/module.ts index 2412224eca6b..f34ed05039d7 100644 --- a/public/app/plugins/panel/graph/module.ts +++ b/public/app/plugins/panel/graph/module.ts @@ -11,7 +11,8 @@ import { DataProcessor } from './data_processor'; import { axesEditorComponent } from './axes_editor'; import config from 'app/core/config'; import TimeSeries from 'app/core/time_series2'; -import { getColorFromHexRgbOrName, LegacyResponseData } from '@grafana/ui'; +import { getColorFromHexRgbOrName, LegacyResponseData, SeriesData } from '@grafana/ui'; +import { getProcessedSeriesData } from 'app/features/dashboard/state/PanelQueryState'; class GraphCtrl extends MetricsPanelCtrl { static template = template; @@ -19,7 +20,7 @@ class GraphCtrl extends MetricsPanelCtrl { renderError: boolean; hiddenSeries: any = {}; seriesList: TimeSeries[] = []; - dataList: LegacyResponseData[] = []; + dataList: SeriesData[] = []; annotations: any = []; alertState: any; @@ -188,9 +189,9 @@ class GraphCtrl extends MetricsPanelCtrl { } onDataReceived(dataList: LegacyResponseData[]) { - this.dataList = dataList; + this.dataList = getProcessedSeriesData(dataList); this.seriesList = this.processor.getSeriesList({ - dataList: dataList, + dataList: this.dataList, range: this.range, }); diff --git a/public/app/plugins/panel/graph/specs/__snapshots__/data_processor.test.ts.snap b/public/app/plugins/panel/graph/specs/__snapshots__/data_processor.test.ts.snap new file mode 100644 index 000000000000..99c3366fff3c --- /dev/null +++ b/public/app/plugins/panel/graph/specs/__snapshots__/data_processor.test.ts.snap @@ -0,0 +1,233 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Graph DataProcessor getTimeSeries from LegacyResponseData Should return a new series for each field 1`] = ` +Array [ + TimeSeries { + "alias": "Value", + "aliasEscaped": "Value", + "bars": Object { + "fillColor": "#7EB26D", + }, + "color": "#7EB26D", + "datapoints": Array [ + Array [ + 1, + 1001, + ], + Array [ + 2, + 1002, + ], + Array [ + 3, + 1003, + ], + ], + "hasMsResolution": false, + "id": "Value", + "label": "Value", + "legend": true, + "stats": Object {}, + "unit": "watt", + "valueFormater": [Function], + }, + TimeSeries { + "alias": "table_data v1", + "aliasEscaped": "table_data v1", + "bars": Object { + "fillColor": "#EAB839", + }, + "color": "#EAB839", + "datapoints": Array [ + Array [ + 0.1, + 1001, + ], + Array [ + 0.2, + 1002, + ], + Array [ + 0.3, + 1003, + ], + ], + "hasMsResolution": false, + "id": "table_data v1", + "label": "table_data v1", + "legend": true, + "stats": Object {}, + "unit": "ohm", + "valueFormater": [Function], + }, + TimeSeries { + "alias": "table_data v2", + "aliasEscaped": "table_data v2", + "bars": Object { + "fillColor": "#6ED0E0", + }, + "color": "#6ED0E0", + "datapoints": Array [ + Array [ + 1.1, + 1001, + ], + Array [ + 2.2, + 1002, + ], + Array [ + 3.3, + 1003, + ], + ], + "hasMsResolution": false, + "id": "table_data v2", + "label": "table_data v2", + "legend": true, + "stats": Object {}, + "unit": undefined, + "valueFormater": [Function], + }, + TimeSeries { + "alias": "series v1", + "aliasEscaped": "series v1", + "bars": Object { + "fillColor": "#EF843C", + }, + "color": "#EF843C", + "datapoints": Array [ + Array [ + 0.1, + 1001, + ], + Array [ + 0.2, + 1002, + ], + Array [ + 0.3, + 1003, + ], + ], + "hasMsResolution": false, + "id": "series v1", + "label": "series v1", + "legend": true, + "stats": Object {}, + "unit": undefined, + "valueFormater": [Function], + }, + TimeSeries { + "alias": "series v2", + "aliasEscaped": "series v2", + "bars": Object { + "fillColor": "#E24D42", + }, + "color": "#E24D42", + "datapoints": Array [ + Array [ + 1.1, + 1001, + ], + Array [ + 2.2, + 1002, + ], + Array [ + 3.3, + 1003, + ], + ], + "hasMsResolution": false, + "id": "series v2", + "label": "series v2", + "legend": true, + "stats": Object {}, + "unit": undefined, + "valueFormater": [Function], + }, +] +`; + +exports[`Graph DataProcessor getTimeSeries from LegacyResponseData Should return single histogram 1`] = ` +Array [ + TimeSeries { + "alias": "Count", + "aliasEscaped": "Count", + "bars": Object { + "fillColor": "#7EB26D", + }, + "color": "#7EB26D", + "datapoints": Array [ + Array [ + 1, + 1001, + ], + Array [ + 2, + 1002, + ], + Array [ + 3, + 1003, + ], + Array [ + 0.1, + 1001, + ], + Array [ + 0.2, + 1002, + ], + Array [ + 0.3, + 1003, + ], + Array [ + 1.1, + 1001, + ], + Array [ + 2.2, + 1002, + ], + Array [ + 3.3, + 1003, + ], + Array [ + 0.1, + 1001, + ], + Array [ + 0.2, + 1002, + ], + Array [ + 0.3, + 1003, + ], + Array [ + 1.1, + 1001, + ], + Array [ + 2.2, + 1002, + ], + Array [ + 3.3, + 1003, + ], + ], + "hasMsResolution": false, + "id": "Value", + "label": "Value", + "legend": true, + "stats": Object {}, + "unit": "watt", + "valueFormater": [Function], + }, +] +`; diff --git a/public/app/plugins/panel/graph/specs/data_processor.test.ts b/public/app/plugins/panel/graph/specs/data_processor.test.ts index b919bb0f3b18..d8b791bd3863 100644 --- a/public/app/plugins/panel/graph/specs/data_processor.test.ts +++ b/public/app/plugins/panel/graph/specs/data_processor.test.ts @@ -1,62 +1,60 @@ import { DataProcessor } from '../data_processor'; +import { getProcessedSeriesData } from 'app/features/dashboard/state/PanelQueryState'; describe('Graph DataProcessor', () => { const panel: any = { - xaxis: {}, + xaxis: { mode: 'series' }, + aliasColors: {}, }; const processor = new DataProcessor(panel); - describe('Given default xaxis options and query that returns docs', () => { - beforeEach(() => { - panel.xaxis.mode = 'time'; - panel.xaxis.name = 'hostname'; - panel.xaxis.values = []; - - processor.getSeriesList({ - dataList: [ - { - type: 'docs', - datapoints: [{ hostname: 'server1', avg: 10 }], - }, + describe('getTimeSeries from LegacyResponseData', () => { + // Try each type of data + const dataList = getProcessedSeriesData([ + { + alias: 'First (time_series)', + datapoints: [[1, 1001], [2, 1002], [3, 1003]], + unit: 'watt', + }, + { + name: 'table_data', + columns: [ + { text: 'time' }, + { text: 'v1', unit: 'ohm' }, + { text: 'v2' }, // no unit + { text: 'string' }, // skipped ], - }); - }); - - it('Should automatically set xaxis mode to field', () => { - expect(panel.xaxis.mode).toBe('field'); - }); - }); - - describe('getDataFieldNames(', () => { - const dataList = [ + rows: [ + [1001, 0.1, 1.1, 'a'], // a + [1002, 0.2, 2.2, 'b'], // b + [1003, 0.3, 3.3, 'c'], // c + ], + }, { - type: 'docs', - datapoints: [ - { - hostname: 'server1', - valueField: 11, - nested: { - prop1: 'server2', - value2: 23, - }, - }, + name: 'series', + fields: [ + { name: 'v1' }, // first + { name: 'v2' }, // second + { name: 'string' }, // skip + { name: 'time' }, // Time is last column ], + rows: [[0.1, 1.1, 'a', 1001], [0.2, 2.2, 'b', 1002], [0.3, 3.3, 'c', 1003]], }, - ]; + ]); - it('Should return all field names', () => { - const fields = processor.getDataFieldNames(dataList, false); - expect(fields).toContain('hostname'); - expect(fields).toContain('valueField'); - expect(fields).toContain('nested.prop1'); - expect(fields).toContain('nested.value2'); + it('Should return a new series for each field', () => { + panel.xaxis.mode = 'series'; + const series = processor.getSeriesList({ dataList }); + expect(series.length).toEqual(5); + expect(series).toMatchSnapshot(); }); - it('Should return all number fields', () => { - const fields = processor.getDataFieldNames(dataList, true); - expect(fields).toContain('valueField'); - expect(fields).toContain('nested.value2'); + it('Should return single histogram', () => { + panel.xaxis.mode = 'histogram'; + const series = processor.getSeriesList({ dataList }); + expect(series.length).toEqual(1); + expect(series).toMatchSnapshot(); }); }); }); From f12d47ef52f9d423c41542a490925dc25960e93a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Sun, 12 May 2019 14:15:23 +0200 Subject: [PATCH 002/166] Chore: Typescript no-implicit any fixes progress (#17018) * Chore: Typescript no-implicit any fixes progress * Fixed tests * Updated snapshot --- .../src/components/Select/Select.tsx | 16 ++--- packages/grafana-ui/src/types/navModel.ts | 2 + public/app/core/angular_wrappers.ts | 2 - .../AppNotifications/AppNotificationItem.tsx | 4 +- .../AppNotifications/AppNotificationList.tsx | 8 +-- .../components/OrgActionBar/OrgActionBar.tsx | 4 +- .../components/PageHeader/PageHeader.test.tsx | 4 +- .../PermissionList/AddPermission.tsx | 6 +- .../PermissionList/PermissionListItem.tsx | 12 ++-- .../core/components/PluginHelp/PluginHelp.tsx | 3 +- .../core/components/Select/MetricSelect.tsx | 6 +- .../components/Select/TeamPicker.test.tsx | 1 + .../app/core/components/Select/TeamPicker.tsx | 6 +- .../components/Select/UserPicker.test.tsx | 1 + .../app/core/components/Select/UserPicker.tsx | 6 +- .../SharedPreferences/SharedPreferences.tsx | 4 +- .../components/code_editor/code_editor.ts | 8 +-- .../components/colorpicker/spectrum_picker.ts | 4 +- public/app/core/components/navbar/navbar.html | 12 ---- public/app/core/components/navbar/navbar.ts | 54 --------------- .../core/components/query_part/query_part.ts | 12 ++-- .../query_part/query_part_editor.ts | 22 +++--- public/app/core/components/scroll/scroll.ts | 3 +- .../core/components/search/SearchField.tsx | 1 + .../core/components/search/SearchResult.tsx | 67 ------------------- public/app/core/components/search/search.ts | 25 ++++--- .../core/components/search/search_results.ts | 14 ++-- .../sidemenu/BottomNavLinks.test.tsx | 8 ++- .../components/sidemenu/BottomNavLinks.tsx | 7 +- .../components/sidemenu/BottomSection.tsx | 5 +- .../components/sidemenu/SideMenuDropDown.tsx | 3 +- .../BottomNavLinks.test.tsx.snap | 4 +- public/app/core/core.ts | 2 - .../__snapshots__/TeamMemberRow.test.tsx.snap | 6 +- public/app/types/acl.ts | 2 + 35 files changed, 111 insertions(+), 233 deletions(-) delete mode 100644 public/app/core/components/navbar/navbar.html delete mode 100644 public/app/core/components/navbar/navbar.ts delete mode 100644 public/app/core/components/search/SearchResult.tsx diff --git a/packages/grafana-ui/src/components/Select/Select.tsx b/packages/grafana-ui/src/components/Select/Select.tsx index f36f78a50fea..da2b0229c627 100644 --- a/packages/grafana-ui/src/components/Select/Select.tsx +++ b/packages/grafana-ui/src/components/Select/Select.tsx @@ -55,11 +55,11 @@ export interface CommonProps { onCloseMenu?: () => void; } -export interface SelectProps { +export interface SelectProps extends CommonProps { options: Array>; } -interface AsyncProps { +interface AsyncProps extends CommonProps { defaultOptions: boolean; loadOptions: (query: string) => Promise>>; loadingMessage?: () => string; @@ -95,9 +95,8 @@ export const MenuList = (props: any) => { ); }; -export class Select extends PureComponent & SelectProps> { - static defaultProps = { - width: null, +export class Select extends PureComponent> { + static defaultProps: Partial> = { className: '', isDisabled: false, isSearchable: true, @@ -108,7 +107,7 @@ export class Select extends PureComponent & SelectProps> { isLoading: false, backspaceRemovesValue: true, maxMenuHeight: 300, - menuIsOpen: false, + isOpen: false, components: { Option: SelectOption, SingleValue, @@ -201,9 +200,8 @@ export class Select extends PureComponent & SelectProps> { } } -export class AsyncSelect extends PureComponent & AsyncProps> { - static defaultProps = { - width: null, +export class AsyncSelect extends PureComponent> { + static defaultProps: Partial> = { className: '', components: {}, loadingMessage: () => 'Loading...', diff --git a/packages/grafana-ui/src/types/navModel.ts b/packages/grafana-ui/src/types/navModel.ts index 2f1018eed9ce..7d23f222e149 100644 --- a/packages/grafana-ui/src/types/navModel.ts +++ b/packages/grafana-ui/src/types/navModel.ts @@ -7,11 +7,13 @@ export interface NavModelItem { id?: string; active?: boolean; hideFromTabs?: boolean; + hideFromMenu?: boolean; divider?: boolean; children?: NavModelItem[]; breadcrumbs?: NavModelBreadcrumb[]; target?: string; parentItem?: NavModelItem; + showOrgSwitcher?: boolean; } export interface NavModel { diff --git a/public/app/core/angular_wrappers.ts b/public/app/core/angular_wrappers.ts index 6da0ca1a44df..30163be0edf5 100644 --- a/public/app/core/angular_wrappers.ts +++ b/public/app/core/angular_wrappers.ts @@ -4,7 +4,6 @@ import { AnnotationQueryEditor as StackdriverAnnotationQueryEditor } from 'app/p import { PasswordStrength } from './components/PasswordStrength'; import PageHeader from './components/PageHeader/PageHeader'; import EmptyListCTA from './components/EmptyListCTA/EmptyListCTA'; -import { SearchResult } from './components/search/SearchResult'; import { TagFilter } from './components/TagFilter/TagFilter'; import { SideMenu } from './components/sidemenu/SideMenu'; import { MetricSelect } from './components/Select/MetricSelect'; @@ -20,7 +19,6 @@ export function registerAngularDirectives() { react2AngularDirective('appNotificationsList', AppNotificationList, []); react2AngularDirective('pageHeader', PageHeader, ['model', 'noTabs']); react2AngularDirective('emptyListCta', EmptyListCTA, ['model']); - react2AngularDirective('searchResult', SearchResult, []); react2AngularDirective('searchField', SearchField, [ 'query', 'autoFocus', diff --git a/public/app/core/components/AppNotifications/AppNotificationItem.tsx b/public/app/core/components/AppNotifications/AppNotificationItem.tsx index d1fc506d54cd..f1617a0a6351 100644 --- a/public/app/core/components/AppNotifications/AppNotificationItem.tsx +++ b/public/app/core/components/AppNotifications/AppNotificationItem.tsx @@ -4,11 +4,11 @@ import { AlertBox } from '../AlertBox/AlertBox'; interface Props { appNotification: AppNotification; - onClearNotification: (id) => void; + onClearNotification: (id: number) => void; } export default class AppNotificationItem extends Component { - shouldComponentUpdate(nextProps) { + shouldComponentUpdate(nextProps: Props) { return this.props.appNotification.id !== nextProps.appNotification.id; } diff --git a/public/app/core/components/AppNotifications/AppNotificationList.tsx b/public/app/core/components/AppNotifications/AppNotificationList.tsx index c91f8372384f..991ac37eda6c 100644 --- a/public/app/core/components/AppNotifications/AppNotificationList.tsx +++ b/public/app/core/components/AppNotifications/AppNotificationList.tsx @@ -20,12 +20,12 @@ export class AppNotificationList extends PureComponent { componentDidMount() { const { notifyApp } = this.props; - appEvents.on('alert-warning', options => notifyApp(createWarningNotification(options[0], options[1]))); - appEvents.on('alert-success', options => notifyApp(createSuccessNotification(options[0], options[1]))); - appEvents.on('alert-error', options => notifyApp(createErrorNotification(options[0], options[1]))); + appEvents.on('alert-warning', (options: string[]) => notifyApp(createWarningNotification(options[0], options[1]))); + appEvents.on('alert-success', (options: string[]) => notifyApp(createSuccessNotification(options[0], options[1]))); + appEvents.on('alert-error', (options: string[]) => notifyApp(createErrorNotification(options[0], options[1]))); } - onClearAppNotification = id => { + onClearAppNotification = (id: number) => { this.props.clearAppNotification(id); }; diff --git a/public/app/core/components/OrgActionBar/OrgActionBar.tsx b/public/app/core/components/OrgActionBar/OrgActionBar.tsx index f83d5c957f74..016c47776686 100644 --- a/public/app/core/components/OrgActionBar/OrgActionBar.tsx +++ b/public/app/core/components/OrgActionBar/OrgActionBar.tsx @@ -14,10 +14,10 @@ export interface Props { export default class OrgActionBar extends PureComponent { render() { const { searchQuery, layoutMode, onSetLayoutMode, linkButton, setSearchQuery, target } = this.props; - const linkProps = { href: linkButton.href, target: undefined }; + const linkProps = { href: linkButton.href }; if (target) { - linkProps.target = target; + (linkProps as any).target = target; } return ( diff --git a/public/app/core/components/PageHeader/PageHeader.test.tsx b/public/app/core/components/PageHeader/PageHeader.test.tsx index a9ba8d008a3a..1999831a6d55 100644 --- a/public/app/core/components/PageHeader/PageHeader.test.tsx +++ b/public/app/core/components/PageHeader/PageHeader.test.tsx @@ -1,9 +1,9 @@ import React from 'react'; import PageHeader from './PageHeader'; -import { shallow } from 'enzyme'; +import { shallow, ShallowWrapper } from 'enzyme'; describe('PageHeader', () => { - let wrapper; + let wrapper: ShallowWrapper; describe('when the nav tree has a node with a title', () => { beforeAll(() => { diff --git a/public/app/core/components/PermissionList/AddPermission.tsx b/public/app/core/components/PermissionList/AddPermission.tsx index d55ec3511ea0..b668229939ff 100644 --- a/public/app/core/components/PermissionList/AddPermission.tsx +++ b/public/app/core/components/PermissionList/AddPermission.tsx @@ -22,7 +22,7 @@ class AddPermissions extends Component { showPermissionLevels: true, }; - constructor(props) { + constructor(props: Props) { super(props); this.state = this.getCleanState(); } @@ -36,7 +36,7 @@ class AddPermissions extends Component { }; } - onTypeChanged = evt => { + onTypeChanged = (evt: any) => { const type = evt.target.value as AclTarget; switch (type) { @@ -65,7 +65,7 @@ class AddPermissions extends Component { this.setState({ permission: permission.value }); }; - onSubmit = async evt => { + onSubmit = async (evt: React.SyntheticEvent) => { evt.preventDefault(); await this.props.onAddPermission(this.state); this.setState(this.getCleanState()); diff --git a/public/app/core/components/PermissionList/PermissionListItem.tsx b/public/app/core/components/PermissionList/PermissionListItem.tsx index b949209d6a38..f590f5fd8ae3 100644 --- a/public/app/core/components/PermissionList/PermissionListItem.tsx +++ b/public/app/core/components/PermissionList/PermissionListItem.tsx @@ -1,13 +1,13 @@ import React, { PureComponent } from 'react'; -import { Select } from '@grafana/ui'; +import { Select, SelectOptionItem } from '@grafana/ui'; import { dashboardPermissionLevels, DashboardAcl, PermissionLevel } from 'app/types/acl'; import { FolderInfo } from 'app/types'; -const setClassNameHelper = inherited => { +const setClassNameHelper = (inherited: boolean) => { return inherited ? 'gf-form-disabled' : ''; }; -function ItemAvatar({ item }) { +function ItemAvatar({ item }: { item: DashboardAcl }) { if (item.userAvatarUrl) { return ; } @@ -21,7 +21,7 @@ function ItemAvatar({ item }) { return ; } -function ItemDescription({ item }) { +function ItemDescription({ item }: { item: DashboardAcl }) { if (item.userId) { return (User); } @@ -39,8 +39,8 @@ interface Props { } export default class PermissionsListItem extends PureComponent { - onPermissionChanged = option => { - this.props.onPermissionChanged(this.props.item, option.value as PermissionLevel); + onPermissionChanged = (option: SelectOptionItem) => { + this.props.onPermissionChanged(this.props.item, option.value); }; onRemoveItem = () => { diff --git a/public/app/core/components/PluginHelp/PluginHelp.tsx b/public/app/core/components/PluginHelp/PluginHelp.tsx index c37498afc459..677fb254314e 100644 --- a/public/app/core/components/PluginHelp/PluginHelp.tsx +++ b/public/app/core/components/PluginHelp/PluginHelp.tsx @@ -1,4 +1,5 @@ import React, { PureComponent } from 'react'; +// @ts-ignore import Remarkable from 'remarkable'; import { getBackendSrv } from '../../services/backend_srv'; @@ -37,7 +38,7 @@ export class PluginHelp extends PureComponent { getBackendSrv() .get(`/api/plugins/${plugin.id}/markdown/${type}`) - .then(response => { + .then((response: string) => { const markdown = new Remarkable(); const helpHtml = markdown.render(response); diff --git a/public/app/core/components/Select/MetricSelect.tsx b/public/app/core/components/Select/MetricSelect.tsx index e4b6cfb8abd9..aa0ea5d40c45 100644 --- a/public/app/core/components/Select/MetricSelect.tsx +++ b/public/app/core/components/Select/MetricSelect.tsx @@ -19,13 +19,13 @@ interface State { } export class MetricSelect extends React.Component { - static defaultProps = { + static defaultProps: Partial = { variables: [], options: [], isSearchable: true, }; - constructor(props) { + constructor(props: Props) { super(props); this.state = { options: [] }; } @@ -45,7 +45,7 @@ export class MetricSelect extends React.Component { return nextProps.value !== this.props.value || !_.isEqual(nextOptions, this.state.options); } - buildOptions({ variables = [], options }) { + buildOptions({ variables = [], options }: Props) { return variables.length > 0 ? [this.getVariablesGroup(), ...options] : options; } diff --git a/public/app/core/components/Select/TeamPicker.test.tsx b/public/app/core/components/Select/TeamPicker.test.tsx index 3db9f7bb4eb4..8ee09461c7fa 100644 --- a/public/app/core/components/Select/TeamPicker.test.tsx +++ b/public/app/core/components/Select/TeamPicker.test.tsx @@ -1,4 +1,5 @@ import React from 'react'; +// @ts-ignore import renderer from 'react-test-renderer'; import { TeamPicker } from './TeamPicker'; diff --git a/public/app/core/components/Select/TeamPicker.tsx b/public/app/core/components/Select/TeamPicker.tsx index 8d9e1d48d810..16df350ad67f 100644 --- a/public/app/core/components/Select/TeamPicker.tsx +++ b/public/app/core/components/Select/TeamPicker.tsx @@ -23,7 +23,7 @@ export interface State { export class TeamPicker extends Component { debouncedSearch: any; - constructor(props) { + constructor(props: Props) { super(props); this.state = { isLoading: false }; this.search = this.search.bind(this); @@ -42,8 +42,8 @@ export class TeamPicker extends Component { query = ''; } - return backendSrv.get(`/api/teams/search?perpage=10&page=1&query=${query}`).then(result => { - const teams = result.teams.map(team => { + return backendSrv.get(`/api/teams/search?perpage=10&page=1&query=${query}`).then((result: any) => { + const teams = result.teams.map((team: any) => { return { id: team.id, value: team.id, diff --git a/public/app/core/components/Select/UserPicker.test.tsx b/public/app/core/components/Select/UserPicker.test.tsx index 054ca643700e..b1dddb48cff0 100644 --- a/public/app/core/components/Select/UserPicker.test.tsx +++ b/public/app/core/components/Select/UserPicker.test.tsx @@ -1,4 +1,5 @@ import React from 'react'; +// @ts-ignore import renderer from 'react-test-renderer'; import { UserPicker } from './UserPicker'; diff --git a/public/app/core/components/Select/UserPicker.tsx b/public/app/core/components/Select/UserPicker.tsx index ff4ae32f0683..ba054a20620c 100644 --- a/public/app/core/components/Select/UserPicker.tsx +++ b/public/app/core/components/Select/UserPicker.tsx @@ -24,7 +24,7 @@ export interface State { export class UserPicker extends Component { debouncedSearch: any; - constructor(props) { + constructor(props: Props) { super(props); this.state = { isLoading: false }; this.search = this.search.bind(this); @@ -45,8 +45,8 @@ export class UserPicker extends Component { return backendSrv .get(`/api/org/users?query=${query}&limit=10`) - .then(result => { - return result.map(user => ({ + .then((result: any) => { + return result.map((user: any) => ({ id: user.userId, value: user.userId, label: user.login === user.email ? user.login : `${user.login} - ${user.email}`, diff --git a/public/app/core/components/SharedPreferences/SharedPreferences.tsx b/public/app/core/components/SharedPreferences/SharedPreferences.tsx index a39eefcec4b3..3b804ba47051 100644 --- a/public/app/core/components/SharedPreferences/SharedPreferences.tsx +++ b/public/app/core/components/SharedPreferences/SharedPreferences.tsx @@ -27,7 +27,7 @@ const timezones = [ export class SharedPreferences extends PureComponent { backendSrv: BackendSrv = getBackendSrv(); - constructor(props) { + constructor(props: Props) { super(props); this.state = { @@ -72,7 +72,7 @@ export class SharedPreferences extends PureComponent { }); } - onSubmitForm = async event => { + onSubmitForm = async (event: React.SyntheticEvent) => { event.preventDefault(); const { homeDashboardId, theme, timezone } = this.state; diff --git a/public/app/core/components/code_editor/code_editor.ts b/public/app/core/components/code_editor/code_editor.ts index ca9023e86570..542454988bd6 100644 --- a/public/app/core/components/code_editor/code_editor.ts +++ b/public/app/core/components/code_editor/code_editor.ts @@ -55,7 +55,7 @@ const DEFAULT_SNIPPETS = true; const editorTemplate = `
`; -function link(scope, elem, attrs) { +function link(scope: any, elem: any, attrs: any) { // Options const langMode = attrs.mode || DEFAULT_MODE; const maxLines = attrs.maxLines || DEFAULT_MAX_LINES; @@ -116,7 +116,7 @@ function link(scope, elem, attrs) { }); // Sync with outer scope - update editor content if model has been changed from outside of directive. - scope.$watch('content', (newValue, oldValue) => { + scope.$watch('content', (newValue: any, oldValue: any) => { const editorValue = codeEditor.getValue(); if (newValue !== editorValue && newValue !== oldValue) { scope.$$postDigest(() => { @@ -142,7 +142,7 @@ function link(scope, elem, attrs) { }, }); - function setLangMode(lang) { + function setLangMode(lang: string) { ace.acequire('ace/ext/language_tools'); codeEditor.setOptions({ enableBasicAutocompletion: true, @@ -170,7 +170,7 @@ function link(scope, elem, attrs) { codeEditor.setTheme(theme); } - function setEditorContent(value) { + function setEditorContent(value: string) { codeEditor.setValue(value); codeEditor.clearSelection(); } diff --git a/public/app/core/components/colorpicker/spectrum_picker.ts b/public/app/core/components/colorpicker/spectrum_picker.ts index 4576648df835..d9831aa96440 100644 --- a/public/app/core/components/colorpicker/spectrum_picker.ts +++ b/public/app/core/components/colorpicker/spectrum_picker.ts @@ -13,9 +13,9 @@ export function spectrumPicker() { scope: true, replace: true, template: '', - link: (scope, element, attrs, ngModel) => { + link: (scope: any, element: any, attrs: any, ngModel: any) => { scope.ngModel = ngModel; - scope.onColorChange = color => { + scope.onColorChange = (color: string) => { ngModel.$setViewValue(color); }; }, diff --git a/public/app/core/components/navbar/navbar.html b/public/app/core/components/navbar/navbar.html deleted file mode 100644 index 6d611692efc9..000000000000 --- a/public/app/core/components/navbar/navbar.html +++ /dev/null @@ -1,12 +0,0 @@ - - - diff --git a/public/app/core/components/navbar/navbar.ts b/public/app/core/components/navbar/navbar.ts deleted file mode 100644 index f4de87451728..000000000000 --- a/public/app/core/components/navbar/navbar.ts +++ /dev/null @@ -1,54 +0,0 @@ -import coreModule from '../../core_module'; -import appEvents from 'app/core/app_events'; -import { NavModel } from '@grafana/ui'; - -export class NavbarCtrl { - model: NavModel; - - /** @ngInject */ - constructor() {} - - showSearch() { - appEvents.emit('show-dash-search'); - } - - navItemClicked(navItem, evt) { - if (navItem.clickHandler) { - navItem.clickHandler(); - evt.preventDefault(); - } - } -} - -export function navbarDirective() { - return { - restrict: 'E', - templateUrl: 'public/app/core/components/navbar/navbar.html', - controller: NavbarCtrl, - bindToController: true, - controllerAs: 'ctrl', - scope: { - model: '=', - }, - link: (scope, elem) => {}, - }; -} - -export function pageH1() { - return { - restrict: 'E', - template: ` -

- - - {{model.header.text}} -

- `, - scope: { - model: '=', - }, - }; -} - -coreModule.directive('pageH1', pageH1); -coreModule.directive('navbar', navbarDirective); diff --git a/public/app/core/components/query_part/query_part.ts b/public/app/core/components/query_part/query_part.ts index 10ac878f4b56..b2466977c229 100644 --- a/public/app/core/components/query_part/query_part.ts +++ b/public/app/core/components/query_part/query_part.ts @@ -40,7 +40,7 @@ export class QueryPart { return this.def.renderer(this, innerExpr); } - hasMultipleParamsInString(strValue, index) { + hasMultipleParamsInString(strValue: string, index: number) { if (strValue.indexOf(',') === -1) { return false; } @@ -48,7 +48,7 @@ export class QueryPart { return this.def.params[index + 1] && this.def.params[index + 1].optional; } - updateParam(strValue, index) { + updateParam(strValue: string, index: number) { // handle optional parameters // if string contains ',' and next param is optional, split and update both if (this.hasMultipleParamsInString(strValue, index)) { @@ -81,7 +81,7 @@ export class QueryPart { } } -export function functionRenderer(part, innerExpr) { +export function functionRenderer(part: any, innerExpr: string) { const str = part.def.type + '('; const parameters = _.map(part.params, (value, index) => { const paramType = part.def.params[index]; @@ -105,14 +105,14 @@ export function functionRenderer(part, innerExpr) { return str + parameters.join(', ') + ')'; } -export function suffixRenderer(part, innerExpr) { +export function suffixRenderer(part: QueryPartDef, innerExpr: string) { return innerExpr + ' ' + part.params[0]; } -export function identityRenderer(part, innerExpr) { +export function identityRenderer(part: QueryPartDef, innerExpr: string) { return part.params[0]; } -export function quotedIdentityRenderer(part, innerExpr) { +export function quotedIdentityRenderer(part: QueryPartDef, innerExpr: string) { return '"' + part.params[0] + '"'; } diff --git a/public/app/core/components/query_part/query_part_editor.ts b/public/app/core/components/query_part/query_part_editor.ts index 4e6b82e151be..4e7221749aa1 100644 --- a/public/app/core/components/query_part/query_part_editor.ts +++ b/public/app/core/components/query_part/query_part_editor.ts @@ -14,7 +14,7 @@ const template = ` `; /** @ngInject */ -export function queryPartEditorDirective($compile, templateSrv) { +export function queryPartEditorDirective(templateSrv: any) { const paramTemplate = ''; return { @@ -25,7 +25,7 @@ export function queryPartEditorDirective($compile, templateSrv) { handleEvent: '&', debounce: '@', }, - link: function postLink($scope, elem) { + link: function postLink($scope: any, elem: any) { const part = $scope.part; const partDef = part.def; const $paramsContainer = elem.find('.query-part-parameters'); @@ -33,7 +33,7 @@ export function queryPartEditorDirective($compile, templateSrv) { $scope.partActions = []; - function clickFuncParam(this: any, paramIndex) { + function clickFuncParam(this: any, paramIndex: number) { /*jshint validthis:true */ const $link = $(this); const $input = $link.next(); @@ -53,7 +53,7 @@ export function queryPartEditorDirective($compile, templateSrv) { } } - function inputBlur(this: any, paramIndex) { + function inputBlur(this: any, paramIndex: number) { /*jshint validthis:true */ const $input = $(this); const $link = $input.prev(); @@ -72,7 +72,7 @@ export function queryPartEditorDirective($compile, templateSrv) { $link.show(); } - function inputKeyPress(this: any, paramIndex, e) { + function inputKeyPress(this: any, paramIndex: number, e: any) { /*jshint validthis:true */ if (e.which === 13) { inputBlur.call(this, paramIndex); @@ -84,12 +84,12 @@ export function queryPartEditorDirective($compile, templateSrv) { this.style.width = (3 + this.value.length) * 8 + 'px'; } - function addTypeahead($input, param, paramIndex) { + function addTypeahead($input: JQuery, param: any, paramIndex: number) { if (!param.options && !param.dynamicLookup) { return; } - const typeaheadSource = (query, callback) => { + const typeaheadSource = (query: string, callback: any) => { if (param.options) { let options = param.options; if (param.type === 'int') { @@ -101,7 +101,7 @@ export function queryPartEditorDirective($compile, templateSrv) { } $scope.$apply(() => { - $scope.handleEvent({ $event: { name: 'get-param-options' } }).then(result => { + $scope.handleEvent({ $event: { name: 'get-param-options' } }).then((result: any) => { const dynamicOptions = _.map(result, op => { return _.escape(op.value); }); @@ -116,7 +116,7 @@ export function queryPartEditorDirective($compile, templateSrv) { source: typeaheadSource, minLength: 0, items: 1000, - updater: value => { + updater: (value: string) => { value = _.unescape(value); setTimeout(() => { inputBlur.call($input[0], paramIndex); @@ -138,12 +138,12 @@ export function queryPartEditorDirective($compile, templateSrv) { } $scope.showActionsMenu = () => { - $scope.handleEvent({ $event: { name: 'get-part-actions' } }).then(res => { + $scope.handleEvent({ $event: { name: 'get-part-actions' } }).then((res: any) => { $scope.partActions = res; }); }; - $scope.triggerPartAction = action => { + $scope.triggerPartAction = (action: string) => { $scope.handleEvent({ $event: { name: 'action', action: action } }); }; diff --git a/public/app/core/components/scroll/scroll.ts b/public/app/core/components/scroll/scroll.ts index 49931ecaac45..fe7e729bb190 100644 --- a/public/app/core/components/scroll/scroll.ts +++ b/public/app/core/components/scroll/scroll.ts @@ -1,4 +1,5 @@ import $ from 'jquery'; +// @ts-ignore import baron from 'baron'; import coreModule from 'app/core/core_module'; @@ -14,7 +15,7 @@ const scrollerClass = 'baron__scroller'; export function geminiScrollbar() { return { restrict: 'A', - link: (scope, elem, attrs) => { + link: (scope: any, elem: any, attrs: any) => { let scrollRoot = elem.parent(); const scroller = elem; diff --git a/public/app/core/components/search/SearchField.tsx b/public/app/core/components/search/SearchField.tsx index 5b6dd03165f5..a72782e21c75 100644 --- a/public/app/core/components/search/SearchField.tsx +++ b/public/app/core/components/search/SearchField.tsx @@ -1,4 +1,5 @@ import React, { useContext } from 'react'; +// @ts-ignore import tinycolor from 'tinycolor2'; import { SearchQuery } from './search'; import { css, cx } from 'emotion'; diff --git a/public/app/core/components/search/SearchResult.tsx b/public/app/core/components/search/SearchResult.tsx deleted file mode 100644 index 13333c168f91..000000000000 --- a/public/app/core/components/search/SearchResult.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import React from 'react'; -import classNames from 'classnames'; - -export class SearchResult extends React.Component { - constructor(props) { - super(props); - - this.state = { - search: '', - }; - } - - render() { - return this.state.search.sections.map(section => { - return ; - }); - } -} - -export interface SectionProps { - section: any; -} - -export class SearchResultSection extends React.Component { - constructor(props) { - super(props); - } - - renderItem(item) { - return ( - - - - - -
{item.title}
-
-
- ); - } - - toggleSection = () => { - this.props.section.toggle(); - }; - - render() { - const collapseClassNames = classNames({ - fa: true, - 'fa-plus': !this.props.section.expanded, - 'fa-minus': this.props.section.expanded, - 'search-section__header__toggle': true, - }); - - return ( -
-
- - {this.props.section.title} - -
- {this.props.section.expanded && ( -
{this.props.section.items.map(this.renderItem)}
- )} -
- ); - } -} diff --git a/public/app/core/components/search/search.ts b/public/app/core/components/search/search.ts index 9cf8e9cd8c12..8728cbb1f348 100644 --- a/public/app/core/components/search/search.ts +++ b/public/app/core/components/search/search.ts @@ -6,6 +6,7 @@ import { contextSrv } from 'app/core/services/context_srv'; import appEvents from 'app/core/app_events'; import { parse, SearchParserOptions, SearchParserResult } from 'search-query-parser'; import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv'; + export interface SearchQuery { query: string; parsedQuery: SearchParserResult; @@ -32,6 +33,11 @@ class SearchQueryParser { } } +interface SelectedIndicies { + dashboardIndex?: number; + folderIndex?: number; +} + export class SearchCtrl { isOpen: boolean; query: SearchQuery; @@ -49,7 +55,7 @@ export class SearchCtrl { queryParser: SearchQueryParser; /** @ngInject */ - constructor($scope, private $location, private $timeout, private searchSrv: SearchSrv) { + constructor($scope: any, private $location: any, private $timeout: any, private searchSrv: SearchSrv) { appEvents.on('show-dash-search', this.openSearch.bind(this), $scope); appEvents.on('hide-dash-search', this.closeSearch.bind(this), $scope); appEvents.on('search-query', debounce(this.search.bind(this), 500), $scope); @@ -88,7 +94,7 @@ export class SearchCtrl { appEvents.emit('search-query'); } - openSearch(evt, payload) { + openSearch(evt: any, payload: any) { if (this.isOpen) { this.closeSearch(); return; @@ -166,7 +172,7 @@ export class SearchCtrl { }, 100); } - moveSelection(direction) { + moveSelection(direction: number) { if (this.results.length === 0) { return; } @@ -252,14 +258,14 @@ export class SearchCtrl { return query.query === '' && query.starred === false && query.tags.length === 0; } - filterByTag(tag) { + filterByTag(tag: string) { if (_.indexOf(this.query.tags, tag) === -1) { this.query.tags.push(tag); this.search(); } } - removeTag(tag, evt) { + removeTag(tag: string, evt: any) { this.query.tags = _.without(this.query.tags, tag); this.search(); this.giveSearchFocus = true; @@ -298,14 +304,11 @@ export class SearchCtrl { this.moveSelection(0); } - private getFlattenedResultForNavigation(): Array<{ - folderIndex: number; - dashboardIndex: number; - }> { + private getFlattenedResultForNavigation(): SelectedIndicies[] { let folderIndex = 0; - return _.flatMap(this.results, s => { - let result = []; + return _.flatMap(this.results, (s: any) => { + let result: SelectedIndicies[] = []; result.push({ folderIndex: folderIndex, diff --git a/public/app/core/components/search/search_results.ts b/public/app/core/components/search/search_results.ts index 35ee1365e222..20cd49d3443e 100644 --- a/public/app/core/components/search/search_results.ts +++ b/public/app/core/components/search/search_results.ts @@ -10,15 +10,15 @@ export class SearchResultsCtrl { editable: boolean; /** @ngInject */ - constructor(private $location) {} + constructor(private $location: any) {} - toggleFolderExpand(section) { + toggleFolderExpand(section: any) { if (section.toggle) { if (!section.expanded && this.onFolderExpanding) { this.onFolderExpanding(); } - section.toggle(section).then(f => { + section.toggle(section).then((f: any) => { if (this.editable && f.expanded) { if (f.items) { _.each(f.items, i => { @@ -34,7 +34,7 @@ export class SearchResultsCtrl { } } - navigateToFolder(section, evt) { + navigateToFolder(section: any, evt: any) { this.$location.path(section.url); if (evt) { @@ -43,7 +43,7 @@ export class SearchResultsCtrl { } } - toggleSelection(item, evt) { + toggleSelection(item: any, evt: any) { item.checked = !item.checked; if (item.items) { @@ -62,14 +62,14 @@ export class SearchResultsCtrl { } } - onItemClick(item) { + onItemClick(item: any) { //Check if one string can be found in the other if (this.$location.path().indexOf(item.url) > -1 || item.url.indexOf(this.$location.path()) > -1) { appEvents.emit('hide-dash-search'); } } - selectTag(tag, evt) { + selectTag(tag: any, evt: any) { if (this.onTagSelected) { this.onTagSelected({ $tag: tag }); } diff --git a/public/app/core/components/sidemenu/BottomNavLinks.test.tsx b/public/app/core/components/sidemenu/BottomNavLinks.test.tsx index 5ba4503da139..d59973fe02d6 100644 --- a/public/app/core/components/sidemenu/BottomNavLinks.test.tsx +++ b/public/app/core/components/sidemenu/BottomNavLinks.test.tsx @@ -10,7 +10,9 @@ jest.mock('../../app_events', () => ({ const setup = (propOverrides?: object) => { const props = Object.assign( { - link: {}, + link: { + text: 'Hello', + }, user: { id: 1, isGrafanaAdmin: false, @@ -87,9 +89,9 @@ describe('Functions', () => { const wrapper = setup(); const mockEvent = { preventDefault: jest.fn() }; it('should emit show modal event if url matches shortcut', () => { - const child = { url: '/shortcuts' }; + const child = { url: '/shortcuts', text: 'hello' }; const instance = wrapper.instance() as BottomNavLinks; - instance.itemClicked(mockEvent, child); + instance.itemClicked(mockEvent as any, child); expect(appEvents.emit).toHaveBeenCalledWith('show-modal', { templateHtml: '' }); }); diff --git a/public/app/core/components/sidemenu/BottomNavLinks.tsx b/public/app/core/components/sidemenu/BottomNavLinks.tsx index e1665c9ebc5a..fee58bad15fc 100644 --- a/public/app/core/components/sidemenu/BottomNavLinks.tsx +++ b/public/app/core/components/sidemenu/BottomNavLinks.tsx @@ -1,14 +1,15 @@ import React, { PureComponent } from 'react'; import appEvents from '../../app_events'; import { User } from '../../services/context_srv'; +import { NavModelItem } from '@grafana/ui'; export interface Props { - link: any; + link: NavModelItem; user: User; } class BottomNavLinks extends PureComponent { - itemClicked = (event, child) => { + itemClicked = (event: React.SyntheticEvent, child: NavModelItem) => { if (child.url === '/shortcuts') { event.preventDefault(); appEvents.emit('show-modal', { @@ -57,7 +58,7 @@ class BottomNavLinks extends PureComponent { link.children.map((child, index) => { if (!child.hideFromMenu) { return ( -
  • +
  • this.itemClicked(event, child)}> {child.icon && } {child.text} diff --git a/public/app/core/components/sidemenu/BottomSection.tsx b/public/app/core/components/sidemenu/BottomSection.tsx index 85754a910fa0..f0668eaf4dd7 100644 --- a/public/app/core/components/sidemenu/BottomSection.tsx +++ b/public/app/core/components/sidemenu/BottomSection.tsx @@ -4,10 +4,11 @@ import SignIn from './SignIn'; import BottomNavLinks from './BottomNavLinks'; import { contextSrv } from 'app/core/services/context_srv'; import config from '../../config'; +import { NavModelItem } from '@grafana/ui'; export default function BottomSection() { - const navTree: any = _.cloneDeep(config.bootData.navTree); - const bottomNav: any = _.filter(navTree, item => item.hideFromMenu); + const navTree: NavModelItem[] = _.cloneDeep(config.bootData.navTree); + const bottomNav: NavModelItem[] = _.filter(navTree, item => item.hideFromMenu); const isSignedIn = contextSrv.isSignedIn; const user = contextSrv.user; diff --git a/public/app/core/components/sidemenu/SideMenuDropDown.tsx b/public/app/core/components/sidemenu/SideMenuDropDown.tsx index db2172039c6f..b3959d55d4a7 100644 --- a/public/app/core/components/sidemenu/SideMenuDropDown.tsx +++ b/public/app/core/components/sidemenu/SideMenuDropDown.tsx @@ -1,8 +1,9 @@ import React, { FC } from 'react'; import DropDownChild from './DropDownChild'; +import { NavModelItem } from '@grafana/ui'; interface Props { - link: any; + link: NavModelItem; } const SideMenuDropDown: FC = props => { diff --git a/public/app/core/components/sidemenu/__snapshots__/BottomNavLinks.test.tsx.snap b/public/app/core/components/sidemenu/__snapshots__/BottomNavLinks.test.tsx.snap index ae8c9c753aa2..8b15bb0ae361 100644 --- a/public/app/core/components/sidemenu/__snapshots__/BottomNavLinks.test.tsx.snap +++ b/public/app/core/components/sidemenu/__snapshots__/BottomNavLinks.test.tsx.snap @@ -67,7 +67,9 @@ exports[`Render should render component 1`] = ` > + > + Hello +
  • diff --git a/public/app/core/core.ts b/public/app/core/core.ts index c7f03781710c..ba4230cfe451 100644 --- a/public/app/core/core.ts +++ b/public/app/core/core.ts @@ -20,7 +20,6 @@ import { colors } from '@grafana/ui/'; import { searchDirective } from './components/search/search'; import { infoPopover } from './components/info_popover'; -import { navbarDirective } from './components/navbar/navbar'; import { arrayJoin } from './directives/array_join'; import { liveSrv } from './live/live_srv'; import { Emitter } from './utils/emitter'; @@ -56,7 +55,6 @@ export { registerAngularDirectives, arrayJoin, coreModule, - navbarDirective, searchDirective, liveSrv, layoutSelector, diff --git a/public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap b/public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap index 6072b1046fcc..46e465f3c312 100644 --- a/public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap +++ b/public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap @@ -97,9 +97,9 @@ exports[`Render when feature toggle editorsCanAdmin is turned off should not ren isDisabled={false} isLoading={false} isMulti={false} + isOpen={false} isSearchable={false} maxMenuHeight={300} - menuIsOpen={false} onChange={[Function]} openMenuOnFocus={false} options={ @@ -123,7 +123,6 @@ exports[`Render when feature toggle editorsCanAdmin is turned off should not ren "value": 0, } } - width={null} /> @@ -183,9 +182,9 @@ exports[`Render when feature toggle editorsCanAdmin is turned on should render p isDisabled={false} isLoading={false} isMulti={false} + isOpen={false} isSearchable={false} maxMenuHeight={300} - menuIsOpen={false} onChange={[Function]} openMenuOnFocus={false} options={ @@ -209,7 +208,6 @@ exports[`Render when feature toggle editorsCanAdmin is turned on should render p "value": 0, } } - width={null} /> diff --git a/public/app/types/acl.ts b/public/app/types/acl.ts index 55e9bff620bc..977791f41596 100644 --- a/public/app/types/acl.ts +++ b/public/app/types/acl.ts @@ -39,6 +39,8 @@ export interface DashboardAcl { name?: string; inherited?: boolean; sortRank?: number; + userAvatarUrl?: string; + teamAvatarUrl?: string; } export interface DashboardPermissionInfo { From aa400d54e1320423363604b96d97f87d7b4d9a85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Sun, 12 May 2019 20:03:44 +0200 Subject: [PATCH 003/166] Select: Fixed isOpen issue --- packages/grafana-ui/src/components/Select/Select.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/grafana-ui/src/components/Select/Select.tsx b/packages/grafana-ui/src/components/Select/Select.tsx index da2b0229c627..d2c784ca8839 100644 --- a/packages/grafana-ui/src/components/Select/Select.tsx +++ b/packages/grafana-ui/src/components/Select/Select.tsx @@ -107,7 +107,6 @@ export class Select extends PureComponent> { isLoading: false, backspaceRemovesValue: true, maxMenuHeight: 300, - isOpen: false, components: { Option: SelectOption, SingleValue, From ce38de4ad7c8a0b89d3b2a4e63168b4783a8af23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Sun, 12 May 2019 20:18:58 +0200 Subject: [PATCH 004/166] Chore: Updated snapshot --- .../features/teams/__snapshots__/TeamMemberRow.test.tsx.snap | 2 -- 1 file changed, 2 deletions(-) diff --git a/public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap b/public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap index 46e465f3c312..96ff1b4cbc99 100644 --- a/public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap +++ b/public/app/features/teams/__snapshots__/TeamMemberRow.test.tsx.snap @@ -97,7 +97,6 @@ exports[`Render when feature toggle editorsCanAdmin is turned off should not ren isDisabled={false} isLoading={false} isMulti={false} - isOpen={false} isSearchable={false} maxMenuHeight={300} onChange={[Function]} @@ -182,7 +181,6 @@ exports[`Render when feature toggle editorsCanAdmin is turned on should render p isDisabled={false} isLoading={false} isMulti={false} - isOpen={false} isSearchable={false} maxMenuHeight={300} onChange={[Function]} From 0efb8821f9fa1e5c213280f1c94f87befead290c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hugo=20H=C3=A4ggmark?= Date: Mon, 13 May 2019 07:47:07 +0200 Subject: [PATCH 005/166] Chore: Lowered implicit anys limit to 5386 Progress: #14714 --- scripts/ci-frontend-metrics.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/ci-frontend-metrics.sh b/scripts/ci-frontend-metrics.sh index 85464aff3e0a..e1bcc3a0031a 100755 --- a/scripts/ci-frontend-metrics.sh +++ b/scripts/ci-frontend-metrics.sh @@ -2,7 +2,7 @@ echo -e "Collecting code stats (typescript errors & more)" -ERROR_COUNT_LIMIT=5564 +ERROR_COUNT_LIMIT=5386 DIRECTIVES_LIMIT=172 CONTROLLERS_LIMIT=139 From 2fff8f77dcdc90ab9a4890eeed95d8f3dced370b Mon Sep 17 00:00:00 2001 From: zhulongcheng Date: Mon, 13 May 2019 14:45:54 +0800 Subject: [PATCH 006/166] move log package to /infra (#17023) ref #14679 Signed-off-by: zhulongcheng --- pkg/api/app_routes.go | 2 +- pkg/api/avatar/avatar.go | 2 +- pkg/api/dashboard.go | 2 +- pkg/api/frontendsettings.go | 2 +- pkg/api/http_server.go | 2 +- pkg/api/live/conn.go | 2 +- pkg/api/live/hub.go | 2 +- pkg/api/live/stream_manager.go | 2 +- pkg/api/login.go | 2 +- pkg/api/login_oauth.go | 2 +- pkg/api/playlist.go | 2 +- pkg/api/playlist_play.go | 2 +- pkg/api/pluginproxy/ds_proxy.go | 2 +- pkg/api/pluginproxy/ds_proxy_test.go | 2 +- pkg/api/pluginproxy/pluginproxy.go | 2 +- pkg/cmd/grafana-server/main.go | 2 +- pkg/cmd/grafana-server/server.go | 2 +- pkg/components/imguploader/azureblobuploader.go | 2 +- pkg/components/imguploader/gcsuploader.go | 2 +- pkg/components/imguploader/imguploader.go | 2 +- pkg/components/imguploader/s3uploader.go | 2 +- pkg/components/securejsondata/securejsondata.go | 2 +- pkg/{ => infra}/log/file.go | 0 pkg/{ => infra}/log/file_test.go | 0 pkg/{ => infra}/log/handlers.go | 0 pkg/{ => infra}/log/interface.go | 0 pkg/{ => infra}/log/log.go | 0 pkg/{ => infra}/log/log_writer.go | 0 pkg/{ => infra}/log/log_writer_test.go | 0 pkg/{ => infra}/log/syslog.go | 0 pkg/{ => infra}/log/syslog_windows.go | 0 pkg/infra/metrics/service.go | 2 +- pkg/infra/remotecache/database_storage.go | 2 +- pkg/infra/remotecache/database_storage_test.go | 2 +- pkg/infra/remotecache/remotecache.go | 2 +- pkg/infra/serverlock/serverlock.go | 2 +- pkg/infra/serverlock/serverlock_test.go | 2 +- pkg/infra/tracing/tracing.go | 2 +- pkg/infra/usagestats/service.go | 2 +- pkg/login/social/common.go | 2 +- pkg/login/social/social.go | 2 +- pkg/middleware/middleware.go | 2 +- pkg/middleware/recovery.go | 2 +- pkg/models/context.go | 2 +- pkg/plugins/datasource/wrapper/datasource_plugin_wrapper.go | 2 +- .../datasource/wrapper/datasource_plugin_wrapper_test.go | 2 +- pkg/plugins/datasource_plugin.go | 2 +- pkg/plugins/hclog-wrapper.go | 2 +- pkg/plugins/plugins.go | 2 +- pkg/plugins/update_checker.go | 2 +- pkg/services/alerting/engine.go | 2 +- pkg/services/alerting/eval_context.go | 2 +- pkg/services/alerting/eval_handler.go | 2 +- pkg/services/alerting/extractor.go | 2 +- pkg/services/alerting/notifier.go | 2 +- pkg/services/alerting/notifiers/alertmanager.go | 2 +- pkg/services/alerting/notifiers/alertmanager_test.go | 2 +- pkg/services/alerting/notifiers/base.go | 2 +- pkg/services/alerting/notifiers/dingding.go | 2 +- pkg/services/alerting/notifiers/discord.go | 2 +- pkg/services/alerting/notifiers/email.go | 2 +- pkg/services/alerting/notifiers/googlechat.go | 2 +- pkg/services/alerting/notifiers/hipchat.go | 2 +- pkg/services/alerting/notifiers/kafka.go | 2 +- pkg/services/alerting/notifiers/line.go | 2 +- pkg/services/alerting/notifiers/opsgenie.go | 2 +- pkg/services/alerting/notifiers/pagerduty.go | 2 +- pkg/services/alerting/notifiers/pushover.go | 2 +- pkg/services/alerting/notifiers/sensu.go | 2 +- pkg/services/alerting/notifiers/slack.go | 2 +- pkg/services/alerting/notifiers/teams.go | 2 +- pkg/services/alerting/notifiers/telegram.go | 2 +- pkg/services/alerting/notifiers/threema.go | 2 +- pkg/services/alerting/notifiers/victorops.go | 2 +- pkg/services/alerting/notifiers/webhook.go | 2 +- pkg/services/alerting/reader.go | 2 +- pkg/services/alerting/result_handler.go | 2 +- pkg/services/alerting/scheduler.go | 2 +- pkg/services/alerting/test_notification.go | 2 +- pkg/services/auth/auth_token.go | 2 +- pkg/services/auth/auth_token_test.go | 2 +- pkg/services/cleanup/cleanup.go | 2 +- pkg/services/dashboards/dashboard_service.go | 2 +- pkg/services/guardian/guardian.go | 2 +- pkg/services/ldap/ldap.go | 2 +- pkg/services/ldap/ldap_login_test.go | 2 +- pkg/services/ldap/ldap_test.go | 2 +- pkg/services/ldap/settings.go | 2 +- pkg/services/login/login.go | 2 +- pkg/services/notifications/notifications.go | 2 +- pkg/services/provisioning/dashboards/config_reader.go | 2 +- pkg/services/provisioning/dashboards/config_reader_test.go | 2 +- pkg/services/provisioning/dashboards/dashboard.go | 2 +- pkg/services/provisioning/dashboards/file_reader.go | 2 +- pkg/services/provisioning/dashboards/file_reader_linux_test.go | 2 +- pkg/services/provisioning/dashboards/file_reader_test.go | 2 +- pkg/services/provisioning/datasources/config_reader.go | 2 +- pkg/services/provisioning/datasources/config_reader_test.go | 2 +- pkg/services/provisioning/datasources/datasources.go | 2 +- pkg/services/provisioning/datasources/types.go | 2 +- pkg/services/provisioning/notifiers/alert_notifications.go | 2 +- pkg/services/provisioning/notifiers/config_reader.go | 2 +- pkg/services/provisioning/notifiers/config_reader_test.go | 2 +- pkg/services/provisioning/provisioning.go | 2 +- pkg/services/rendering/phantomjs.go | 2 +- pkg/services/rendering/rendering.go | 2 +- pkg/services/sqlstore/logger.go | 2 +- pkg/services/sqlstore/migrator/migrator.go | 2 +- pkg/services/sqlstore/sqlstore.go | 2 +- pkg/services/sqlstore/transactions.go | 2 +- pkg/setting/setting.go | 2 +- pkg/setting/setting_session_test.go | 2 +- pkg/tsdb/azuremonitor/azuremonitor.go | 2 +- pkg/tsdb/cloudwatch/cloudwatch.go | 2 +- pkg/tsdb/elasticsearch/client/client.go | 2 +- pkg/tsdb/elasticsearch/elasticsearch.go | 2 +- pkg/tsdb/graphite/graphite.go | 2 +- pkg/tsdb/influxdb/influxdb.go | 2 +- pkg/tsdb/mssql/mssql.go | 2 +- pkg/tsdb/mysql/mysql.go | 2 +- pkg/tsdb/opentsdb/opentsdb.go | 2 +- pkg/tsdb/postgres/postgres.go | 2 +- pkg/tsdb/prometheus/prometheus.go | 2 +- pkg/tsdb/sql_engine.go | 2 +- pkg/tsdb/stackdriver/stackdriver.go | 2 +- pkg/tsdb/testdata/scenarios.go | 2 +- pkg/tsdb/testdata/testdata.go | 2 +- 127 files changed, 118 insertions(+), 118 deletions(-) rename pkg/{ => infra}/log/file.go (100%) rename pkg/{ => infra}/log/file_test.go (100%) rename pkg/{ => infra}/log/handlers.go (100%) rename pkg/{ => infra}/log/interface.go (100%) rename pkg/{ => infra}/log/log.go (100%) rename pkg/{ => infra}/log/log_writer.go (100%) rename pkg/{ => infra}/log/log_writer_test.go (100%) rename pkg/{ => infra}/log/syslog.go (100%) rename pkg/{ => infra}/log/syslog_windows.go (100%) diff --git a/pkg/api/app_routes.go b/pkg/api/app_routes.go index e85a19dbce81..8e462e176fcb 100644 --- a/pkg/api/app_routes.go +++ b/pkg/api/app_routes.go @@ -7,7 +7,7 @@ import ( "time" "github.com/grafana/grafana/pkg/api/pluginproxy" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/middleware" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" diff --git a/pkg/api/avatar/avatar.go b/pkg/api/avatar/avatar.go index 6cf164285bfb..e01982c8fdab 100644 --- a/pkg/api/avatar/avatar.go +++ b/pkg/api/avatar/avatar.go @@ -22,7 +22,7 @@ import ( "sync" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/setting" "gopkg.in/macaron.v1" diff --git a/pkg/api/dashboard.go b/pkg/api/dashboard.go index 212b56842809..ed153c02efe3 100644 --- a/pkg/api/dashboard.go +++ b/pkg/api/dashboard.go @@ -14,8 +14,8 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/dashdiffs" "github.com/grafana/grafana/pkg/components/simplejson" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - "github.com/grafana/grafana/pkg/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/services/guardian" diff --git a/pkg/api/frontendsettings.go b/pkg/api/frontendsettings.go index e4fb0ed34c01..e881fc1539de 100644 --- a/pkg/api/frontendsettings.go +++ b/pkg/api/frontendsettings.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/util" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/api/http_server.go b/pkg/api/http_server.go index 4f368d8bb0a3..7ec4fbaa3b3c 100644 --- a/pkg/api/http_server.go +++ b/pkg/api/http_server.go @@ -16,8 +16,8 @@ import ( httpstatic "github.com/grafana/grafana/pkg/api/static" "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/remotecache" - "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/middleware" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" diff --git a/pkg/api/live/conn.go b/pkg/api/live/conn.go index 0fae7f75b73c..f6450fa1d63d 100644 --- a/pkg/api/live/conn.go +++ b/pkg/api/live/conn.go @@ -6,7 +6,7 @@ import ( "github.com/gorilla/websocket" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" ) const ( diff --git a/pkg/api/live/hub.go b/pkg/api/live/hub.go index 9708bc515d1c..10eaca4f79d6 100644 --- a/pkg/api/live/hub.go +++ b/pkg/api/live/hub.go @@ -5,7 +5,7 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" ) type hub struct { diff --git a/pkg/api/live/stream_manager.go b/pkg/api/live/stream_manager.go index 00d98286882e..2369bb1f9b51 100644 --- a/pkg/api/live/stream_manager.go +++ b/pkg/api/live/stream_manager.go @@ -6,7 +6,7 @@ import ( "sync" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" ) diff --git a/pkg/api/login.go b/pkg/api/login.go index ebf4cc8db07c..e7fe6db93477 100644 --- a/pkg/api/login.go +++ b/pkg/api/login.go @@ -7,8 +7,8 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/middleware" m "github.com/grafana/grafana/pkg/models" diff --git a/pkg/api/login_oauth.go b/pkg/api/login_oauth.go index a3599bc7a24e..8c5ca6fc7d1d 100644 --- a/pkg/api/login_oauth.go +++ b/pkg/api/login_oauth.go @@ -16,8 +16,8 @@ import ( "golang.org/x/oauth2" "github.com/grafana/grafana/pkg/bus" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/login/social" m "github.com/grafana/grafana/pkg/models" diff --git a/pkg/api/playlist.go b/pkg/api/playlist.go index 0963df7d4c47..bb429847dc01 100644 --- a/pkg/api/playlist.go +++ b/pkg/api/playlist.go @@ -2,7 +2,7 @@ package api import ( "github.com/grafana/grafana/pkg/bus" - _ "github.com/grafana/grafana/pkg/log" + _ "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" ) diff --git a/pkg/api/playlist_play.go b/pkg/api/playlist_play.go index 21c91a1288da..53eab8908d78 100644 --- a/pkg/api/playlist_play.go +++ b/pkg/api/playlist_play.go @@ -6,7 +6,7 @@ import ( "github.com/grafana/grafana/pkg/api/dtos" "github.com/grafana/grafana/pkg/bus" - _ "github.com/grafana/grafana/pkg/log" + _ "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/search" ) diff --git a/pkg/api/pluginproxy/ds_proxy.go b/pkg/api/pluginproxy/ds_proxy.go index fe79fa565950..98fd30cc1c9b 100644 --- a/pkg/api/pluginproxy/ds_proxy.go +++ b/pkg/api/pluginproxy/ds_proxy.go @@ -17,7 +17,7 @@ import ( "golang.org/x/oauth2" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/login/social" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" diff --git a/pkg/api/pluginproxy/ds_proxy_test.go b/pkg/api/pluginproxy/ds_proxy_test.go index c3eccb4a57c9..13c3be3214b8 100644 --- a/pkg/api/pluginproxy/ds_proxy_test.go +++ b/pkg/api/pluginproxy/ds_proxy_test.go @@ -17,7 +17,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/login/social" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" diff --git a/pkg/api/pluginproxy/pluginproxy.go b/pkg/api/pluginproxy/pluginproxy.go index 4ee4e5b8db3a..4c37cd00db86 100644 --- a/pkg/api/pluginproxy/pluginproxy.go +++ b/pkg/api/pluginproxy/pluginproxy.go @@ -10,7 +10,7 @@ import ( "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/util" diff --git a/pkg/cmd/grafana-server/main.go b/pkg/cmd/grafana-server/main.go index 825d48e00764..d836f9a7d703 100644 --- a/pkg/cmd/grafana-server/main.go +++ b/pkg/cmd/grafana-server/main.go @@ -14,8 +14,8 @@ import ( "time" "github.com/grafana/grafana/pkg/extensions" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - "github.com/grafana/grafana/pkg/log" _ "github.com/grafana/grafana/pkg/services/alerting/conditions" _ "github.com/grafana/grafana/pkg/services/alerting/notifiers" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/cmd/grafana-server/server.go b/pkg/cmd/grafana-server/server.go index 2ac326ed35d6..f1823260e16d 100644 --- a/pkg/cmd/grafana-server/server.go +++ b/pkg/cmd/grafana-server/server.go @@ -18,12 +18,12 @@ import ( "github.com/grafana/grafana/pkg/api/routing" "github.com/grafana/grafana/pkg/bus" _ "github.com/grafana/grafana/pkg/extensions" + "github.com/grafana/grafana/pkg/infra/log" _ "github.com/grafana/grafana/pkg/infra/metrics" _ "github.com/grafana/grafana/pkg/infra/remotecache" _ "github.com/grafana/grafana/pkg/infra/serverlock" _ "github.com/grafana/grafana/pkg/infra/tracing" _ "github.com/grafana/grafana/pkg/infra/usagestats" - "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/login" "github.com/grafana/grafana/pkg/login/social" "github.com/grafana/grafana/pkg/middleware" diff --git a/pkg/components/imguploader/azureblobuploader.go b/pkg/components/imguploader/azureblobuploader.go index b37763931c89..bfcb901dd0c2 100644 --- a/pkg/components/imguploader/azureblobuploader.go +++ b/pkg/components/imguploader/azureblobuploader.go @@ -20,7 +20,7 @@ import ( "strings" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/util" ) diff --git a/pkg/components/imguploader/gcsuploader.go b/pkg/components/imguploader/gcsuploader.go index 4513019ad98a..8932e96e59eb 100644 --- a/pkg/components/imguploader/gcsuploader.go +++ b/pkg/components/imguploader/gcsuploader.go @@ -8,7 +8,7 @@ import ( "os" "path" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/util" "golang.org/x/oauth2/google" ) diff --git a/pkg/components/imguploader/imguploader.go b/pkg/components/imguploader/imguploader.go index 422a03d3501a..9aeb4eefb42f 100644 --- a/pkg/components/imguploader/imguploader.go +++ b/pkg/components/imguploader/imguploader.go @@ -5,7 +5,7 @@ import ( "fmt" "regexp" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/setting" ) diff --git a/pkg/components/imguploader/s3uploader.go b/pkg/components/imguploader/s3uploader.go index 9c8af21e39e9..d690f629f577 100644 --- a/pkg/components/imguploader/s3uploader.go +++ b/pkg/components/imguploader/s3uploader.go @@ -15,7 +15,7 @@ import ( "github.com/aws/aws-sdk-go/aws/endpoints" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/util" ) diff --git a/pkg/components/securejsondata/securejsondata.go b/pkg/components/securejsondata/securejsondata.go index 4e7f63601739..dae9584995ad 100644 --- a/pkg/components/securejsondata/securejsondata.go +++ b/pkg/components/securejsondata/securejsondata.go @@ -1,7 +1,7 @@ package securejsondata import ( - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" ) diff --git a/pkg/log/file.go b/pkg/infra/log/file.go similarity index 100% rename from pkg/log/file.go rename to pkg/infra/log/file.go diff --git a/pkg/log/file_test.go b/pkg/infra/log/file_test.go similarity index 100% rename from pkg/log/file_test.go rename to pkg/infra/log/file_test.go diff --git a/pkg/log/handlers.go b/pkg/infra/log/handlers.go similarity index 100% rename from pkg/log/handlers.go rename to pkg/infra/log/handlers.go diff --git a/pkg/log/interface.go b/pkg/infra/log/interface.go similarity index 100% rename from pkg/log/interface.go rename to pkg/infra/log/interface.go diff --git a/pkg/log/log.go b/pkg/infra/log/log.go similarity index 100% rename from pkg/log/log.go rename to pkg/infra/log/log.go diff --git a/pkg/log/log_writer.go b/pkg/infra/log/log_writer.go similarity index 100% rename from pkg/log/log_writer.go rename to pkg/infra/log/log_writer.go diff --git a/pkg/log/log_writer_test.go b/pkg/infra/log/log_writer_test.go similarity index 100% rename from pkg/log/log_writer_test.go rename to pkg/infra/log/log_writer_test.go diff --git a/pkg/log/syslog.go b/pkg/infra/log/syslog.go similarity index 100% rename from pkg/log/syslog.go rename to pkg/infra/log/syslog.go diff --git a/pkg/log/syslog_windows.go b/pkg/infra/log/syslog_windows.go similarity index 100% rename from pkg/log/syslog_windows.go rename to pkg/infra/log/syslog_windows.go diff --git a/pkg/infra/metrics/service.go b/pkg/infra/metrics/service.go index ac1d934e375f..6f981085ffb6 100644 --- a/pkg/infra/metrics/service.go +++ b/pkg/infra/metrics/service.go @@ -3,8 +3,8 @@ package metrics import ( "context" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics/graphitebridge" - "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/setting" ) diff --git a/pkg/infra/remotecache/database_storage.go b/pkg/infra/remotecache/database_storage.go index 16c42054df09..3e15bd9a2cd9 100644 --- a/pkg/infra/remotecache/database_storage.go +++ b/pkg/infra/remotecache/database_storage.go @@ -4,7 +4,7 @@ import ( "context" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/sqlstore" ) diff --git a/pkg/infra/remotecache/database_storage_test.go b/pkg/infra/remotecache/database_storage_test.go index 6e3c8fd4844e..ea7192f93383 100644 --- a/pkg/infra/remotecache/database_storage_test.go +++ b/pkg/infra/remotecache/database_storage_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/sqlstore" "github.com/stretchr/testify/assert" ) diff --git a/pkg/infra/remotecache/remotecache.go b/pkg/infra/remotecache/remotecache.go index c5049f8b27fb..0c04277192f5 100644 --- a/pkg/infra/remotecache/remotecache.go +++ b/pkg/infra/remotecache/remotecache.go @@ -7,7 +7,7 @@ import ( "errors" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/services/sqlstore" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/infra/serverlock/serverlock.go b/pkg/infra/serverlock/serverlock.go index 824fa0484b28..497575681570 100644 --- a/pkg/infra/serverlock/serverlock.go +++ b/pkg/infra/serverlock/serverlock.go @@ -4,7 +4,7 @@ import ( "context" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/services/sqlstore" ) diff --git a/pkg/infra/serverlock/serverlock_test.go b/pkg/infra/serverlock/serverlock_test.go index ccd1c252090d..d72f2a357d95 100644 --- a/pkg/infra/serverlock/serverlock_test.go +++ b/pkg/infra/serverlock/serverlock_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/services/sqlstore" . "github.com/smartystreets/goconvey/convey" ) diff --git a/pkg/infra/tracing/tracing.go b/pkg/infra/tracing/tracing.go index fd7258b7a0ab..2e1b75e81d13 100644 --- a/pkg/infra/tracing/tracing.go +++ b/pkg/infra/tracing/tracing.go @@ -5,7 +5,7 @@ import ( "io" "strings" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/infra/usagestats/service.go b/pkg/infra/usagestats/service.go index ccebf6a17f48..7cda2cbef4b6 100644 --- a/pkg/infra/usagestats/service.go +++ b/pkg/infra/usagestats/service.go @@ -8,7 +8,7 @@ import ( "github.com/grafana/grafana/pkg/login/social" "github.com/grafana/grafana/pkg/services/sqlstore" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/setting" ) diff --git a/pkg/login/social/common.go b/pkg/login/social/common.go index cf2fa3711492..b813e07ab795 100644 --- a/pkg/login/social/common.go +++ b/pkg/login/social/common.go @@ -6,7 +6,7 @@ import ( "net/http" "strings" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" ) type HttpGetResponse struct { diff --git a/pkg/login/social/social.go b/pkg/login/social/social.go index e73e9229a2af..46192ba861e0 100644 --- a/pkg/login/social/social.go +++ b/pkg/login/social/social.go @@ -8,7 +8,7 @@ import ( "golang.org/x/oauth2" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" ) diff --git a/pkg/middleware/middleware.go b/pkg/middleware/middleware.go index f4f60c015593..ec7194a7fc66 100644 --- a/pkg/middleware/middleware.go +++ b/pkg/middleware/middleware.go @@ -9,8 +9,8 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/apikeygen" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/remotecache" - "github.com/grafana/grafana/pkg/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" diff --git a/pkg/middleware/recovery.go b/pkg/middleware/recovery.go index b8ca85fb45b2..33ceff8bc7ef 100644 --- a/pkg/middleware/recovery.go +++ b/pkg/middleware/recovery.go @@ -23,7 +23,7 @@ import ( "gopkg.in/macaron.v1" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) diff --git a/pkg/models/context.go b/pkg/models/context.go index 947e442c2006..f4b8d2c87d5d 100644 --- a/pkg/models/context.go +++ b/pkg/models/context.go @@ -3,7 +3,7 @@ package models import ( "strings" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/setting" "github.com/prometheus/client_golang/prometheus" "gopkg.in/macaron.v1" diff --git a/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper.go b/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper.go index 0af727e14df0..cc88f90f2730 100644 --- a/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper.go +++ b/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper.go @@ -8,7 +8,7 @@ import ( "github.com/grafana/grafana-plugin-model/go/datasource" "github.com/grafana/grafana/pkg/components/null" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/tsdb" ) diff --git a/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper_test.go b/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper_test.go index e312913fc562..2086ea4b9911 100644 --- a/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper_test.go +++ b/pkg/plugins/datasource/wrapper/datasource_plugin_wrapper_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana-plugin-model/go/datasource" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/tsdb" ) diff --git a/pkg/plugins/datasource_plugin.go b/pkg/plugins/datasource_plugin.go index dd4ae6972aaa..57dacbe43b51 100644 --- a/pkg/plugins/datasource_plugin.go +++ b/pkg/plugins/datasource_plugin.go @@ -8,7 +8,7 @@ import ( "time" "github.com/grafana/grafana-plugin-model/go/datasource" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins/datasource/wrapper" "github.com/grafana/grafana/pkg/tsdb" diff --git a/pkg/plugins/hclog-wrapper.go b/pkg/plugins/hclog-wrapper.go index ac50d15f3d88..7bd031565c16 100644 --- a/pkg/plugins/hclog-wrapper.go +++ b/pkg/plugins/hclog-wrapper.go @@ -5,7 +5,7 @@ import ( "io/ioutil" "log" - glog "github.com/grafana/grafana/pkg/log" + glog "github.com/grafana/grafana/pkg/infra/log" hclog "github.com/hashicorp/go-hclog" ) diff --git a/pkg/plugins/plugins.go b/pkg/plugins/plugins.go index 0a031e3a5041..4c75e6b3d581 100644 --- a/pkg/plugins/plugins.go +++ b/pkg/plugins/plugins.go @@ -13,7 +13,7 @@ import ( "strings" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/util" diff --git a/pkg/plugins/update_checker.go b/pkg/plugins/update_checker.go index e61f4cf1df74..1d4cad1399ec 100644 --- a/pkg/plugins/update_checker.go +++ b/pkg/plugins/update_checker.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/setting" "github.com/hashicorp/go-version" ) diff --git a/pkg/services/alerting/engine.go b/pkg/services/alerting/engine.go index db8079583878..c67b59839d79 100644 --- a/pkg/services/alerting/engine.go +++ b/pkg/services/alerting/engine.go @@ -10,7 +10,7 @@ import ( tlog "github.com/opentracing/opentracing-go/log" "github.com/benbjohnson/clock" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/services/alerting/eval_context.go b/pkg/services/alerting/eval_context.go index 02b9955662f0..6358c22a97f1 100644 --- a/pkg/services/alerting/eval_context.go +++ b/pkg/services/alerting/eval_context.go @@ -6,7 +6,7 @@ import ( "time" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) diff --git a/pkg/services/alerting/eval_handler.go b/pkg/services/alerting/eval_handler.go index 097f4bcb2b6b..22d172568f55 100644 --- a/pkg/services/alerting/eval_handler.go +++ b/pkg/services/alerting/eval_handler.go @@ -5,8 +5,8 @@ import ( "strings" "time" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - "github.com/grafana/grafana/pkg/log" ) type DefaultEvalHandler struct { diff --git a/pkg/services/alerting/extractor.go b/pkg/services/alerting/extractor.go index 5b911c5a9adb..c3fcc01ad55e 100644 --- a/pkg/services/alerting/extractor.go +++ b/pkg/services/alerting/extractor.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" ) diff --git a/pkg/services/alerting/notifier.go b/pkg/services/alerting/notifier.go index c28ac49b8945..8c2ac839e439 100644 --- a/pkg/services/alerting/notifier.go +++ b/pkg/services/alerting/notifier.go @@ -6,8 +6,8 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/imguploader" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - "github.com/grafana/grafana/pkg/log" "github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/services/alerting/notifiers/alertmanager.go b/pkg/services/alerting/notifiers/alertmanager.go index 2caa4d5ab587..9febe42505be 100644 --- a/pkg/services/alerting/notifiers/alertmanager.go +++ b/pkg/services/alerting/notifiers/alertmanager.go @@ -6,7 +6,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/alertmanager_test.go b/pkg/services/alerting/notifiers/alertmanager_test.go index 7510742ed172..9197926035ea 100644 --- a/pkg/services/alerting/notifiers/alertmanager_test.go +++ b/pkg/services/alerting/notifiers/alertmanager_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" . "github.com/smartystreets/goconvey/convey" diff --git a/pkg/services/alerting/notifiers/base.go b/pkg/services/alerting/notifiers/base.go index 800505b63801..6bd375b53bcb 100644 --- a/pkg/services/alerting/notifiers/base.go +++ b/pkg/services/alerting/notifiers/base.go @@ -4,7 +4,7 @@ import ( "context" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/dingding.go b/pkg/services/alerting/notifiers/dingding.go index 3e3496622b7e..0aa2ba078f37 100644 --- a/pkg/services/alerting/notifiers/dingding.go +++ b/pkg/services/alerting/notifiers/dingding.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/discord.go b/pkg/services/alerting/notifiers/discord.go index c7178211f0ea..6ed422b1cbb0 100644 --- a/pkg/services/alerting/notifiers/discord.go +++ b/pkg/services/alerting/notifiers/discord.go @@ -10,7 +10,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/services/alerting/notifiers/email.go b/pkg/services/alerting/notifiers/email.go index 6c7bf5edb297..b3f465a2b80c 100644 --- a/pkg/services/alerting/notifiers/email.go +++ b/pkg/services/alerting/notifiers/email.go @@ -5,7 +5,7 @@ import ( "strings" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/services/alerting/notifiers/googlechat.go b/pkg/services/alerting/notifiers/googlechat.go index 1aba15a79282..41f3503640cb 100644 --- a/pkg/services/alerting/notifiers/googlechat.go +++ b/pkg/services/alerting/notifiers/googlechat.go @@ -6,7 +6,7 @@ import ( "time" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/services/alerting/notifiers/hipchat.go b/pkg/services/alerting/notifiers/hipchat.go index 388cec795976..6b94c41065fb 100644 --- a/pkg/services/alerting/notifiers/hipchat.go +++ b/pkg/services/alerting/notifiers/hipchat.go @@ -8,7 +8,7 @@ import ( "fmt" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/kafka.go b/pkg/services/alerting/notifiers/kafka.go index a8a424c87a7c..d7da05499b75 100644 --- a/pkg/services/alerting/notifiers/kafka.go +++ b/pkg/services/alerting/notifiers/kafka.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/line.go b/pkg/services/alerting/notifiers/line.go index 9e3888b8f954..edbec373becd 100644 --- a/pkg/services/alerting/notifiers/line.go +++ b/pkg/services/alerting/notifiers/line.go @@ -5,7 +5,7 @@ import ( "net/url" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/opsgenie.go b/pkg/services/alerting/notifiers/opsgenie.go index 629968b51023..84242ea97691 100644 --- a/pkg/services/alerting/notifiers/opsgenie.go +++ b/pkg/services/alerting/notifiers/opsgenie.go @@ -6,7 +6,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/pagerduty.go b/pkg/services/alerting/notifiers/pagerduty.go index 9f6ce3c2dc89..ab2a36fd86b2 100644 --- a/pkg/services/alerting/notifiers/pagerduty.go +++ b/pkg/services/alerting/notifiers/pagerduty.go @@ -9,7 +9,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/pushover.go b/pkg/services/alerting/notifiers/pushover.go index 8e1903f68ac0..0d23bbf6fb3c 100644 --- a/pkg/services/alerting/notifiers/pushover.go +++ b/pkg/services/alerting/notifiers/pushover.go @@ -9,7 +9,7 @@ import ( "strconv" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/sensu.go b/pkg/services/alerting/notifiers/sensu.go index 21d5d3d9d9e5..b018c53208e8 100644 --- a/pkg/services/alerting/notifiers/sensu.go +++ b/pkg/services/alerting/notifiers/sensu.go @@ -6,7 +6,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/slack.go b/pkg/services/alerting/notifiers/slack.go index ca5f47a322f5..7754b7de71aa 100644 --- a/pkg/services/alerting/notifiers/slack.go +++ b/pkg/services/alerting/notifiers/slack.go @@ -10,7 +10,7 @@ import ( "time" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/services/alerting/notifiers/teams.go b/pkg/services/alerting/notifiers/teams.go index e19357d7b7e2..e33a93f8a0cf 100644 --- a/pkg/services/alerting/notifiers/teams.go +++ b/pkg/services/alerting/notifiers/teams.go @@ -4,7 +4,7 @@ import ( "encoding/json" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/telegram.go b/pkg/services/alerting/notifiers/telegram.go index ab43f3bce356..a5876b77b228 100644 --- a/pkg/services/alerting/notifiers/telegram.go +++ b/pkg/services/alerting/notifiers/telegram.go @@ -8,7 +8,7 @@ import ( "os" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/threema.go b/pkg/services/alerting/notifiers/threema.go index 28a62fade177..2360073d2281 100644 --- a/pkg/services/alerting/notifiers/threema.go +++ b/pkg/services/alerting/notifiers/threema.go @@ -6,7 +6,7 @@ import ( "strings" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/notifiers/victorops.go b/pkg/services/alerting/notifiers/victorops.go index f33b3f4019e0..74988c21ed8f 100644 --- a/pkg/services/alerting/notifiers/victorops.go +++ b/pkg/services/alerting/notifiers/victorops.go @@ -5,7 +5,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/services/alerting/notifiers/webhook.go b/pkg/services/alerting/notifiers/webhook.go index 4045e496af99..7c582a41aeb8 100644 --- a/pkg/services/alerting/notifiers/webhook.go +++ b/pkg/services/alerting/notifiers/webhook.go @@ -3,7 +3,7 @@ package notifiers import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) diff --git a/pkg/services/alerting/reader.go b/pkg/services/alerting/reader.go index d9f20a21c8e6..3f033a746f27 100644 --- a/pkg/services/alerting/reader.go +++ b/pkg/services/alerting/reader.go @@ -5,8 +5,8 @@ import ( "time" "github.com/grafana/grafana/pkg/bus" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - "github.com/grafana/grafana/pkg/log" m "github.com/grafana/grafana/pkg/models" ) diff --git a/pkg/services/alerting/result_handler.go b/pkg/services/alerting/result_handler.go index c8e9e2dc25c7..6f2669ff41a9 100644 --- a/pkg/services/alerting/result_handler.go +++ b/pkg/services/alerting/result_handler.go @@ -5,8 +5,8 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - "github.com/grafana/grafana/pkg/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/annotations" "github.com/grafana/grafana/pkg/services/rendering" diff --git a/pkg/services/alerting/scheduler.go b/pkg/services/alerting/scheduler.go index b7555ae8d898..9a0769d25f24 100644 --- a/pkg/services/alerting/scheduler.go +++ b/pkg/services/alerting/scheduler.go @@ -4,7 +4,7 @@ import ( "math" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" ) diff --git a/pkg/services/alerting/test_notification.go b/pkg/services/alerting/test_notification.go index 22f6a2118b7d..fbb1633d4a5b 100644 --- a/pkg/services/alerting/test_notification.go +++ b/pkg/services/alerting/test_notification.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/null" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" ) diff --git a/pkg/services/auth/auth_token.go b/pkg/services/auth/auth_token.go index dc9936f2f3ff..527d054f6ee9 100644 --- a/pkg/services/auth/auth_token.go +++ b/pkg/services/auth/auth_token.go @@ -8,7 +8,7 @@ import ( "github.com/grafana/grafana/pkg/infra/serverlock" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/services/sqlstore" diff --git a/pkg/services/auth/auth_token_test.go b/pkg/services/auth/auth_token_test.go index b1398834bdc9..802b4602cbfc 100644 --- a/pkg/services/auth/auth_token_test.go +++ b/pkg/services/auth/auth_token_test.go @@ -9,7 +9,7 @@ import ( "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/setting" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/sqlstore" . "github.com/smartystreets/goconvey/convey" diff --git a/pkg/services/cleanup/cleanup.go b/pkg/services/cleanup/cleanup.go index 63d829bccec1..6e07a76f8002 100644 --- a/pkg/services/cleanup/cleanup.go +++ b/pkg/services/cleanup/cleanup.go @@ -8,8 +8,8 @@ import ( "time" "github.com/grafana/grafana/pkg/bus" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/serverlock" - "github.com/grafana/grafana/pkg/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/services/dashboards/dashboard_service.go b/pkg/services/dashboards/dashboard_service.go index 884d993f43c6..bec718700a78 100644 --- a/pkg/services/dashboards/dashboard_service.go +++ b/pkg/services/dashboards/dashboard_service.go @@ -5,7 +5,7 @@ import ( "time" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/guardian" "github.com/grafana/grafana/pkg/util" diff --git a/pkg/services/guardian/guardian.go b/pkg/services/guardian/guardian.go index 366bc90fc377..4d242722d6b1 100644 --- a/pkg/services/guardian/guardian.go +++ b/pkg/services/guardian/guardian.go @@ -4,7 +4,7 @@ import ( "errors" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) diff --git a/pkg/services/ldap/ldap.go b/pkg/services/ldap/ldap.go index 5ff74bd7a3e9..d6b5b69d7525 100644 --- a/pkg/services/ldap/ldap.go +++ b/pkg/services/ldap/ldap.go @@ -12,7 +12,7 @@ import ( LDAP "gopkg.in/ldap.v3" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" models "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) diff --git a/pkg/services/ldap/ldap_login_test.go b/pkg/services/ldap/ldap_login_test.go index 5afed5462463..b8dd502667ea 100644 --- a/pkg/services/ldap/ldap_login_test.go +++ b/pkg/services/ldap/ldap_login_test.go @@ -6,7 +6,7 @@ import ( . "github.com/smartystreets/goconvey/convey" "gopkg.in/ldap.v3" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" ) func TestLdapLogin(t *testing.T) { diff --git a/pkg/services/ldap/ldap_test.go b/pkg/services/ldap/ldap_test.go index c5232a54e2bd..4da041ae1642 100644 --- a/pkg/services/ldap/ldap_test.go +++ b/pkg/services/ldap/ldap_test.go @@ -8,7 +8,7 @@ import ( "gopkg.in/ldap.v3" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" ) diff --git a/pkg/services/ldap/settings.go b/pkg/services/ldap/settings.go index 633920d0a194..de2da2402bfe 100644 --- a/pkg/services/ldap/settings.go +++ b/pkg/services/ldap/settings.go @@ -8,7 +8,7 @@ import ( "github.com/grafana/grafana/pkg/util/errutil" "golang.org/x/xerrors" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) diff --git a/pkg/services/login/login.go b/pkg/services/login/login.go index 9b2a258dea02..791b34e0b30a 100644 --- a/pkg/services/login/login.go +++ b/pkg/services/login/login.go @@ -2,7 +2,7 @@ package login import ( "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/services/quota" diff --git a/pkg/services/notifications/notifications.go b/pkg/services/notifications/notifications.go index 769fdd06fd04..3168fdcd5e95 100644 --- a/pkg/services/notifications/notifications.go +++ b/pkg/services/notifications/notifications.go @@ -11,7 +11,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/events" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/services/provisioning/dashboards/config_reader.go b/pkg/services/provisioning/dashboards/config_reader.go index 50cedc079e33..d004221a3525 100644 --- a/pkg/services/provisioning/dashboards/config_reader.go +++ b/pkg/services/provisioning/dashboards/config_reader.go @@ -7,7 +7,7 @@ import ( "path/filepath" "strings" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" yaml "gopkg.in/yaml.v2" ) diff --git a/pkg/services/provisioning/dashboards/config_reader_test.go b/pkg/services/provisioning/dashboards/config_reader_test.go index 18d8022d62d0..03aa19af11e8 100644 --- a/pkg/services/provisioning/dashboards/config_reader_test.go +++ b/pkg/services/provisioning/dashboards/config_reader_test.go @@ -4,7 +4,7 @@ import ( "os" "testing" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" . "github.com/smartystreets/goconvey/convey" ) diff --git a/pkg/services/provisioning/dashboards/dashboard.go b/pkg/services/provisioning/dashboards/dashboard.go index fd3a824420c6..9cf2e3225f4d 100644 --- a/pkg/services/provisioning/dashboards/dashboard.go +++ b/pkg/services/provisioning/dashboards/dashboard.go @@ -3,7 +3,7 @@ package dashboards import ( "context" "fmt" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/pkg/errors" ) diff --git a/pkg/services/provisioning/dashboards/file_reader.go b/pkg/services/provisioning/dashboards/file_reader.go index 96da9c8f6dfb..61f6be457ee5 100644 --- a/pkg/services/provisioning/dashboards/file_reader.go +++ b/pkg/services/provisioning/dashboards/file_reader.go @@ -16,7 +16,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" ) diff --git a/pkg/services/provisioning/dashboards/file_reader_linux_test.go b/pkg/services/provisioning/dashboards/file_reader_linux_test.go index d62a59a4f4c7..4adeeafe49b4 100644 --- a/pkg/services/provisioning/dashboards/file_reader_linux_test.go +++ b/pkg/services/provisioning/dashboards/file_reader_linux_test.go @@ -6,7 +6,7 @@ import ( "path/filepath" "testing" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" ) var ( diff --git a/pkg/services/provisioning/dashboards/file_reader_test.go b/pkg/services/provisioning/dashboards/file_reader_test.go index efc6052cbe79..668608d79eca 100644 --- a/pkg/services/provisioning/dashboards/file_reader_test.go +++ b/pkg/services/provisioning/dashboards/file_reader_test.go @@ -13,7 +13,7 @@ import ( "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/dashboards" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" . "github.com/smartystreets/goconvey/convey" ) diff --git a/pkg/services/provisioning/datasources/config_reader.go b/pkg/services/provisioning/datasources/config_reader.go index 334ce879e5ad..60794e3b4b03 100644 --- a/pkg/services/provisioning/datasources/config_reader.go +++ b/pkg/services/provisioning/datasources/config_reader.go @@ -6,7 +6,7 @@ import ( "path/filepath" "strings" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "gopkg.in/yaml.v2" ) diff --git a/pkg/services/provisioning/datasources/config_reader_test.go b/pkg/services/provisioning/datasources/config_reader_test.go index 6aba82622141..6bf60b30fc1b 100644 --- a/pkg/services/provisioning/datasources/config_reader_test.go +++ b/pkg/services/provisioning/datasources/config_reader_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" diff --git a/pkg/services/provisioning/datasources/datasources.go b/pkg/services/provisioning/datasources/datasources.go index de6c876baada..f25d717b915f 100644 --- a/pkg/services/provisioning/datasources/datasources.go +++ b/pkg/services/provisioning/datasources/datasources.go @@ -5,7 +5,7 @@ import ( "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" ) diff --git a/pkg/services/provisioning/datasources/types.go b/pkg/services/provisioning/datasources/types.go index bbd072052dd7..d1a76246c9db 100644 --- a/pkg/services/provisioning/datasources/types.go +++ b/pkg/services/provisioning/datasources/types.go @@ -2,7 +2,7 @@ package datasources import ( "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/provisioning/values" ) diff --git a/pkg/services/provisioning/notifiers/alert_notifications.go b/pkg/services/provisioning/notifiers/alert_notifications.go index 3659a73832ee..865e215e38bf 100644 --- a/pkg/services/provisioning/notifiers/alert_notifications.go +++ b/pkg/services/provisioning/notifiers/alert_notifications.go @@ -4,7 +4,7 @@ import ( "errors" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" ) diff --git a/pkg/services/provisioning/notifiers/config_reader.go b/pkg/services/provisioning/notifiers/config_reader.go index 896d5105cedb..5dbb3d87b786 100644 --- a/pkg/services/provisioning/notifiers/config_reader.go +++ b/pkg/services/provisioning/notifiers/config_reader.go @@ -7,7 +7,7 @@ import ( "path/filepath" "strings" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "gopkg.in/yaml.v2" diff --git a/pkg/services/provisioning/notifiers/config_reader_test.go b/pkg/services/provisioning/notifiers/config_reader_test.go index d705bd0d93d9..e2ffb5aa75f8 100644 --- a/pkg/services/provisioning/notifiers/config_reader_test.go +++ b/pkg/services/provisioning/notifiers/config_reader_test.go @@ -4,7 +4,7 @@ import ( "os" "testing" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/services/alerting/notifiers" diff --git a/pkg/services/provisioning/provisioning.go b/pkg/services/provisioning/provisioning.go index 29f2d1391643..7a88aa9e3391 100644 --- a/pkg/services/provisioning/provisioning.go +++ b/pkg/services/provisioning/provisioning.go @@ -5,7 +5,7 @@ import ( "path" "sync" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/pkg/errors" "github.com/grafana/grafana/pkg/registry" diff --git a/pkg/services/rendering/phantomjs.go b/pkg/services/rendering/phantomjs.go index 35389fe7918e..a67d43c3c239 100644 --- a/pkg/services/rendering/phantomjs.go +++ b/pkg/services/rendering/phantomjs.go @@ -10,7 +10,7 @@ import ( "strings" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/middleware" ) diff --git a/pkg/services/rendering/rendering.go b/pkg/services/rendering/rendering.go index 06db73771b26..259b5db2d7af 100644 --- a/pkg/services/rendering/rendering.go +++ b/pkg/services/rendering/rendering.go @@ -10,7 +10,7 @@ import ( plugin "github.com/hashicorp/go-plugin" pluginModel "github.com/grafana/grafana-plugin-model/go/renderer" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/middleware" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" diff --git a/pkg/services/sqlstore/logger.go b/pkg/services/sqlstore/logger.go index 9b0b068c9184..498c2b58c17d 100644 --- a/pkg/services/sqlstore/logger.go +++ b/pkg/services/sqlstore/logger.go @@ -3,7 +3,7 @@ package sqlstore import ( "fmt" - glog "github.com/grafana/grafana/pkg/log" + glog "github.com/grafana/grafana/pkg/infra/log" "github.com/go-xorm/core" ) diff --git a/pkg/services/sqlstore/migrator/migrator.go b/pkg/services/sqlstore/migrator/migrator.go index ce0b2663def4..68820c7feb6a 100644 --- a/pkg/services/sqlstore/migrator/migrator.go +++ b/pkg/services/sqlstore/migrator/migrator.go @@ -5,7 +5,7 @@ import ( _ "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" _ "github.com/lib/pq" _ "github.com/mattn/go-sqlite3" ) diff --git a/pkg/services/sqlstore/sqlstore.go b/pkg/services/sqlstore/sqlstore.go index 116c246cbe34..97b9080ffcfd 100644 --- a/pkg/services/sqlstore/sqlstore.go +++ b/pkg/services/sqlstore/sqlstore.go @@ -14,7 +14,7 @@ import ( "github.com/go-sql-driver/mysql" "github.com/go-xorm/xorm" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/registry" "github.com/grafana/grafana/pkg/services/annotations" diff --git a/pkg/services/sqlstore/transactions.go b/pkg/services/sqlstore/transactions.go index edf29fffb8f3..ed8b6a2309fd 100644 --- a/pkg/services/sqlstore/transactions.go +++ b/pkg/services/sqlstore/transactions.go @@ -5,7 +5,7 @@ import ( "time" "github.com/grafana/grafana/pkg/bus" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" sqlite3 "github.com/mattn/go-sqlite3" ) diff --git a/pkg/setting/setting.go b/pkg/setting/setting.go index 788ea7677c99..192f300021b8 100644 --- a/pkg/setting/setting.go +++ b/pkg/setting/setting.go @@ -20,7 +20,7 @@ import ( "github.com/go-macaron/session" ini "gopkg.in/ini.v1" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/util" ) diff --git a/pkg/setting/setting_session_test.go b/pkg/setting/setting_session_test.go index 7bf31123473e..0a73b47a91d8 100644 --- a/pkg/setting/setting_session_test.go +++ b/pkg/setting/setting_session_test.go @@ -4,7 +4,7 @@ import ( "path/filepath" "testing" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" . "github.com/smartystreets/goconvey/convey" ) diff --git a/pkg/tsdb/azuremonitor/azuremonitor.go b/pkg/tsdb/azuremonitor/azuremonitor.go index 31a42d21a12f..39014bf38dae 100644 --- a/pkg/tsdb/azuremonitor/azuremonitor.go +++ b/pkg/tsdb/azuremonitor/azuremonitor.go @@ -5,7 +5,7 @@ import ( "fmt" "net/http" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/tsdb" ) diff --git a/pkg/tsdb/cloudwatch/cloudwatch.go b/pkg/tsdb/cloudwatch/cloudwatch.go index 56e9bd30e98b..34d57f4d71fc 100644 --- a/pkg/tsdb/cloudwatch/cloudwatch.go +++ b/pkg/tsdb/cloudwatch/cloudwatch.go @@ -10,7 +10,7 @@ import ( "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/ec2/ec2iface" "github.com/aws/aws-sdk-go/service/resourcegroupstaggingapi/resourcegroupstaggingapiiface" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/tsdb" "golang.org/x/sync/errgroup" diff --git a/pkg/tsdb/elasticsearch/client/client.go b/pkg/tsdb/elasticsearch/client/client.go index 131bcdc97844..48f9cce0a5a2 100644 --- a/pkg/tsdb/elasticsearch/client/client.go +++ b/pkg/tsdb/elasticsearch/client/client.go @@ -13,7 +13,7 @@ import ( "time" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/tsdb" "github.com/grafana/grafana/pkg/models" diff --git a/pkg/tsdb/elasticsearch/elasticsearch.go b/pkg/tsdb/elasticsearch/elasticsearch.go index 857b847f0f93..01c9194877c9 100644 --- a/pkg/tsdb/elasticsearch/elasticsearch.go +++ b/pkg/tsdb/elasticsearch/elasticsearch.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/tsdb" "github.com/grafana/grafana/pkg/tsdb/elasticsearch/client" diff --git a/pkg/tsdb/graphite/graphite.go b/pkg/tsdb/graphite/graphite.go index 9a5de205a23a..b74112c3001e 100644 --- a/pkg/tsdb/graphite/graphite.go +++ b/pkg/tsdb/graphite/graphite.go @@ -13,7 +13,7 @@ import ( "golang.org/x/net/context/ctxhttp" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/tsdb" diff --git a/pkg/tsdb/influxdb/influxdb.go b/pkg/tsdb/influxdb/influxdb.go index 6bff961f981f..3b8f365211a5 100644 --- a/pkg/tsdb/influxdb/influxdb.go +++ b/pkg/tsdb/influxdb/influxdb.go @@ -10,7 +10,7 @@ import ( "path" "strings" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/tsdb" diff --git a/pkg/tsdb/mssql/mssql.go b/pkg/tsdb/mssql/mssql.go index 6503632aea3a..81a7e159a868 100644 --- a/pkg/tsdb/mssql/mssql.go +++ b/pkg/tsdb/mssql/mssql.go @@ -8,7 +8,7 @@ import ( _ "github.com/denisenkom/go-mssqldb" "github.com/go-xorm/core" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/tsdb" "github.com/grafana/grafana/pkg/util" diff --git a/pkg/tsdb/mysql/mysql.go b/pkg/tsdb/mysql/mysql.go index 95a9e02598f0..1f569f215db9 100644 --- a/pkg/tsdb/mysql/mysql.go +++ b/pkg/tsdb/mysql/mysql.go @@ -10,7 +10,7 @@ import ( "github.com/go-sql-driver/mysql" "github.com/go-xorm/core" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/tsdb" ) diff --git a/pkg/tsdb/opentsdb/opentsdb.go b/pkg/tsdb/opentsdb/opentsdb.go index d0f61e052335..372f0ef67849 100644 --- a/pkg/tsdb/opentsdb/opentsdb.go +++ b/pkg/tsdb/opentsdb/opentsdb.go @@ -15,7 +15,7 @@ import ( "net/url" "github.com/grafana/grafana/pkg/components/null" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" "github.com/grafana/grafana/pkg/tsdb" diff --git a/pkg/tsdb/postgres/postgres.go b/pkg/tsdb/postgres/postgres.go index 7840a47fb187..dc3a006123b3 100644 --- a/pkg/tsdb/postgres/postgres.go +++ b/pkg/tsdb/postgres/postgres.go @@ -7,7 +7,7 @@ import ( "strconv" "github.com/go-xorm/core" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/tsdb" ) diff --git a/pkg/tsdb/prometheus/prometheus.go b/pkg/tsdb/prometheus/prometheus.go index bb343aea26e7..04fef37c2cf2 100644 --- a/pkg/tsdb/prometheus/prometheus.go +++ b/pkg/tsdb/prometheus/prometheus.go @@ -12,7 +12,7 @@ import ( "net/http" "github.com/grafana/grafana/pkg/components/null" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/tsdb" api "github.com/prometheus/client_golang/api" diff --git a/pkg/tsdb/sql_engine.go b/pkg/tsdb/sql_engine.go index ab7230e9b029..b4ceead85678 100644 --- a/pkg/tsdb/sql_engine.go +++ b/pkg/tsdb/sql_engine.go @@ -12,7 +12,7 @@ import ( "sync" "time" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/components/null" diff --git a/pkg/tsdb/stackdriver/stackdriver.go b/pkg/tsdb/stackdriver/stackdriver.go index 76b346553ad2..e811e70c775d 100644 --- a/pkg/tsdb/stackdriver/stackdriver.go +++ b/pkg/tsdb/stackdriver/stackdriver.go @@ -21,7 +21,7 @@ import ( "github.com/grafana/grafana/pkg/api/pluginproxy" "github.com/grafana/grafana/pkg/components/null" "github.com/grafana/grafana/pkg/components/simplejson" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/plugins" "github.com/grafana/grafana/pkg/setting" diff --git a/pkg/tsdb/testdata/scenarios.go b/pkg/tsdb/testdata/scenarios.go index 964e6f586f33..0a521894f430 100644 --- a/pkg/tsdb/testdata/scenarios.go +++ b/pkg/tsdb/testdata/scenarios.go @@ -9,7 +9,7 @@ import ( "time" "github.com/grafana/grafana/pkg/components/null" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/tsdb" ) diff --git a/pkg/tsdb/testdata/testdata.go b/pkg/tsdb/testdata/testdata.go index c2c2ea3f696c..11b25c73542f 100644 --- a/pkg/tsdb/testdata/testdata.go +++ b/pkg/tsdb/testdata/testdata.go @@ -3,7 +3,7 @@ package testdata import ( "context" - "github.com/grafana/grafana/pkg/log" + "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/tsdb" ) From e0b760e08e1d83805c1286f4ea2b4b7bf263a375 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Mon, 13 May 2019 09:38:19 +0200 Subject: [PATCH 007/166] Chore: No implict any fixes (#17020) --- package.json | 3 +- packages/grafana-ui/src/types/datasource.ts | 6 ++ .../app/core/components/PasswordStrength.tsx | 2 +- .../core/components/TagFilter/TagBadge.tsx | 2 +- .../core/components/TagFilter/TagFilter.tsx | 24 +++--- .../core/components/TagFilter/TagOption.tsx | 2 + .../core/components/TagFilter/TagValue.tsx | 5 +- .../ToggleButtonGroup/ToggleButtonGroup.tsx | 4 +- .../app/core/components/dashboard_selector.ts | 3 +- public/app/core/components/info_popover.ts | 5 +- public/app/core/components/org_switcher.ts | 7 +- .../app/core/components/sql_part/sql_part.ts | 2 +- .../components/sql_part/sql_part_editor.ts | 26 +++--- public/app/core/components/switch.ts | 2 +- public/app/core/jquery_extended.ts | 2 +- public/app/core/logs_model.ts | 10 +-- public/app/core/nav_model_srv.ts | 2 +- public/app/core/partials.ts | 2 +- public/app/core/profiler.ts | 4 +- public/app/core/services/backend_srv.ts | 2 +- public/app/core/services/segment_srv.ts | 84 +++++++++++-------- public/app/core/table_model.ts | 23 +++-- public/app/core/time_series2.ts | 20 ++--- .../app/core/utils/connectWithReduxStore.tsx | 2 +- public/app/features/admin/AdminEditOrgCtrl.ts | 19 +++-- .../app/features/admin/AdminEditUserCtrl.ts | 24 +++--- .../app/features/admin/AdminListOrgsCtrl.ts | 11 ++- .../app/features/admin/AdminListUsersCtrl.ts | 15 ++-- .../app/features/admin/ServerStats.test.tsx | 1 + public/app/features/admin/StyleGuideCtrl.ts | 6 +- public/app/features/admin/index.ts | 12 +-- .../features/alerting/AlertRuleItem.test.tsx | 2 +- .../app/features/alerting/AlertRuleItem.tsx | 1 + public/app/features/alerting/AlertTabCtrl.ts | 65 +++++++------- .../alerting/NotificationsEditCtrl.ts | 31 ++++--- .../alerting/NotificationsListCtrl.ts | 13 +-- public/app/features/alerting/StateHistory.tsx | 6 +- .../alerting/state/ThresholdMapper.ts | 6 +- .../app/features/alerting/state/alertDef.ts | 8 +- .../features/alerting/state/reducers.test.ts | 4 +- .../app/features/alerting/state/reducers.ts | 18 ++-- .../features/alerting/state/selectors.test.ts | 6 +- .../app/features/alerting/state/selectors.ts | 6 +- .../dashboard/dashgrid/PanelChrome.tsx | 2 +- public/app/features/explore/Explore.tsx | 2 +- public/app/features/explore/QueryRow.tsx | 21 ++--- public/app/features/explore/Wrapper.tsx | 1 + public/app/features/org/state/actions.ts | 9 +- public/app/features/panel/panel_ctrl.ts | 2 +- .../datasource/prometheus/datasource.ts | 2 +- public/app/types/alerting.ts | 4 +- scripts/ci-frontend-metrics.sh | 2 +- yarn.lock | 19 ++++- 53 files changed, 321 insertions(+), 241 deletions(-) diff --git a/package.json b/package.json index 69309e2e341b..85c953f907a0 100644 --- a/package.json +++ b/package.json @@ -187,6 +187,7 @@ "dependencies": { "@babel/polyfill": "7.2.5", "@torkelo/react-select": "2.4.1", + "@types/react-redux": "^7.0.8", "@types/reselect": "2.2.0", "angular": "1.6.6", "angular-bindonce": "0.3.1", @@ -201,8 +202,8 @@ "d3": "4.13.0", "d3-scale-chromatic": "1.3.3", "eventemitter3": "2.0.3", - "file-saver": "1.3.8", "fast-text-encoding": "^1.0.0", + "file-saver": "1.3.8", "immutable": "3.8.2", "jquery": "3.4.0", "lodash": "4.17.11", diff --git a/packages/grafana-ui/src/types/datasource.ts b/packages/grafana-ui/src/types/datasource.ts index 2622efd3ed50..3be0bae09dd8 100644 --- a/packages/grafana-ui/src/types/datasource.ts +++ b/packages/grafana-ui/src/types/datasource.ts @@ -78,6 +78,7 @@ export interface DataSourcePluginMeta extends PluginMeta { logs?: boolean; explore?: boolean; annotations?: boolean; + alerting?: boolean; mixed?: boolean; hasQueryHelp?: boolean; category?: string; @@ -181,6 +182,11 @@ export abstract class DataSourceApi< * static information about the datasource */ meta?: DataSourcePluginMeta; + + /** + * Used by alerting to check if query contains template variables + */ + targetContainsTemplate?(query: TQuery): boolean; } export abstract class ExploreDataSourceApi< diff --git a/public/app/core/components/PasswordStrength.tsx b/public/app/core/components/PasswordStrength.tsx index 1d676a00a375..6c6bb697f653 100644 --- a/public/app/core/components/PasswordStrength.tsx +++ b/public/app/core/components/PasswordStrength.tsx @@ -5,7 +5,7 @@ export interface Props { } export class PasswordStrength extends React.Component { - constructor(props) { + constructor(props: Props) { super(props); } diff --git a/public/app/core/components/TagFilter/TagBadge.tsx b/public/app/core/components/TagFilter/TagBadge.tsx index b00b95b70cba..d7a0c8977958 100644 --- a/public/app/core/components/TagFilter/TagBadge.tsx +++ b/public/app/core/components/TagFilter/TagBadge.tsx @@ -9,7 +9,7 @@ export interface Props { } export class TagBadge extends React.Component { - constructor(props) { + constructor(props: Props) { super(props); } diff --git a/public/app/core/components/TagFilter/TagFilter.tsx b/public/app/core/components/TagFilter/TagFilter.tsx index 967792a9f7b2..89d3e8469b6b 100644 --- a/public/app/core/components/TagFilter/TagFilter.tsx +++ b/public/app/core/components/TagFilter/TagFilter.tsx @@ -1,10 +1,14 @@ +// Libraries import React from 'react'; -import { NoOptionsMessage, IndicatorsContainer, resetSelectStyles } from '@grafana/ui'; +// @ts-ignore +import { components } from '@torkelo/react-select'; +// @ts-ignore import AsyncSelect from '@torkelo/react-select/lib/Async'; +// Components import { TagOption } from './TagOption'; import { TagBadge } from './TagBadge'; -import { components } from '@torkelo/react-select'; +import { NoOptionsMessage, IndicatorsContainer, resetSelectStyles } from '@grafana/ui'; import { escapeStringForRegex } from '../FilterInput/FilterInput'; export interface Props { @@ -16,12 +20,12 @@ export interface Props { export class TagFilter extends React.Component { inlineTags: boolean; - constructor(props) { + constructor(props: Props) { super(props); } - onLoadOptions = query => { - return this.props.tagOptions().then(options => { + onLoadOptions = (query: string) => { + return this.props.tagOptions().then((options: any[]) => { return options.map(option => ({ value: option.term, label: option.term, @@ -47,11 +51,11 @@ export class TagFilter extends React.Component { placeholder: 'Tags', loadingMessage: () => 'Loading...', noOptionsMessage: () => 'No tags found', - getOptionValue: i => i.value, - getOptionLabel: i => i.label, + getOptionValue: (i: any) => i.value, + getOptionLabel: (i: any) => i.label, value: tags, styles: resetSelectStyles(), - filterOption: (option, searchQuery) => { + filterOption: (option: any, searchQuery: string) => { const regex = RegExp(escapeStringForRegex(searchQuery), 'i'); return regex.test(option.value); }, @@ -59,10 +63,10 @@ export class TagFilter extends React.Component { Option: TagOption, IndicatorsContainer, NoOptionsMessage, - MultiValueLabel: () => { + MultiValueLabel: (): any => { return null; // We want the whole tag to be clickable so we use MultiValueRemove instead }, - MultiValueRemove: props => { + MultiValueRemove: (props: any) => { const { data } = props; return ( diff --git a/public/app/core/components/TagFilter/TagOption.tsx b/public/app/core/components/TagFilter/TagOption.tsx index 9db15aaca0b3..4da6202bf3e8 100644 --- a/public/app/core/components/TagFilter/TagOption.tsx +++ b/public/app/core/components/TagFilter/TagOption.tsx @@ -1,4 +1,6 @@ +// Libraries import React from 'react'; +// @ts-ignore import { components } from '@torkelo/react-select'; import { OptionProps } from 'react-select/lib/components/Option'; import { TagBadge } from './TagBadge'; diff --git a/public/app/core/components/TagFilter/TagValue.tsx b/public/app/core/components/TagFilter/TagValue.tsx index 43e41c7fdc29..0406ead16a62 100644 --- a/public/app/core/components/TagFilter/TagValue.tsx +++ b/public/app/core/components/TagFilter/TagValue.tsx @@ -9,18 +9,17 @@ export interface Props { } export class TagValue extends React.Component { - constructor(props) { + constructor(props: Props) { super(props); this.onClick = this.onClick.bind(this); } - onClick(event) { + onClick(event: React.SyntheticEvent) { this.props.onRemove(this.props.value, event); } render() { const { value } = this.props; - return ; } } diff --git a/public/app/core/components/ToggleButtonGroup/ToggleButtonGroup.tsx b/public/app/core/components/ToggleButtonGroup/ToggleButtonGroup.tsx index e550afc20c3f..ce1f80c8dcae 100644 --- a/public/app/core/components/ToggleButtonGroup/ToggleButtonGroup.tsx +++ b/public/app/core/components/ToggleButtonGroup/ToggleButtonGroup.tsx @@ -21,7 +21,7 @@ export default class ToggleButtonGroup extends PureComponent void; + onChange?: (value: any) => void; selected?: boolean; value: any; className?: string; @@ -37,7 +37,7 @@ export const ToggleButton: FC = ({ tooltip, onChange, }) => { - const onClick = event => { + const onClick = (event: React.SyntheticEvent) => { event.stopPropagation(); if (onChange) { onChange(value); diff --git a/public/app/core/components/dashboard_selector.ts b/public/app/core/components/dashboard_selector.ts index e1809f3d42cd..f312c77f6a85 100644 --- a/public/app/core/components/dashboard_selector.ts +++ b/public/app/core/components/dashboard_selector.ts @@ -1,4 +1,5 @@ import coreModule from 'app/core/core_module'; +import { BackendSrv } from '../services/backend_srv'; const template = ` @@ -9,7 +10,7 @@ export class DashboardSelectorCtrl { options: any; /** @ngInject */ - constructor(private backendSrv) {} + constructor(private backendSrv: BackendSrv) {} $onInit() { this.options = [{ value: 0, text: 'Default' }]; diff --git a/public/app/core/components/info_popover.ts b/public/app/core/components/info_popover.ts index 2ada91b09f1b..9c5694188d6e 100644 --- a/public/app/core/components/info_popover.ts +++ b/public/app/core/components/info_popover.ts @@ -1,5 +1,6 @@ import _ from 'lodash'; import coreModule from 'app/core/core_module'; +// @ts-ignore import Drop from 'tether-drop'; export function infoPopover() { @@ -7,7 +8,7 @@ export function infoPopover() { restrict: 'E', template: '', transclude: true, - link: (scope, elem, attrs, ctrl, transclude) => { + link: (scope: any, elem: any, attrs: any, transclude: any) => { const offset = attrs.offset || '0 -10px'; const position = attrs.position || 'right middle'; let classes = 'drop-help drop-hide-out-of-bounds'; @@ -23,7 +24,7 @@ export function infoPopover() { elem.addClass('gf-form-help-icon--' + attrs.mode); } - transclude((clone, newScope) => { + transclude((clone: any, newScope: any) => { const content = document.createElement('div'); content.className = 'markdown-html'; diff --git a/public/app/core/components/org_switcher.ts b/public/app/core/components/org_switcher.ts index dc8f00f0fdb4..0e25482e190a 100644 --- a/public/app/core/components/org_switcher.ts +++ b/public/app/core/components/org_switcher.ts @@ -1,6 +1,7 @@ import coreModule from 'app/core/core_module'; import { contextSrv } from 'app/core/services/context_srv'; import config from 'app/core/config'; +import { BackendSrv } from '../services/backend_srv'; const template = ` + x ); diff --git a/public/app/features/org/state/actions.ts b/public/app/features/org/state/actions.ts index 52793698a45d..fc8742d12226 100644 --- a/public/app/features/org/state/actions.ts +++ b/public/app/features/org/state/actions.ts @@ -1,9 +1,6 @@ -import { ThunkAction } from 'redux-thunk'; -import { Organization, StoreState } from 'app/types'; +import { Organization, ThunkResult } from 'app/types'; import { getBackendSrv } from 'app/core/services/backend_srv'; -type ThunkResult = ThunkAction; - export enum ActionTypes { LoadOrganization = 'LOAD_ORGANIZATION', SetOrganizationName = 'SET_ORGANIZATION_NAME', @@ -31,7 +28,7 @@ export const setOrganizationName = (orgName: string) => ({ export type Action = LoadOrganizationAction | SetOrganizationNameAction; -export function loadOrganization(): ThunkResult { +export function loadOrganization(): ThunkResult { return async dispatch => { const organizationResponse = await getBackendSrv().get('/api/org'); dispatch(organizationLoaded(organizationResponse)); @@ -40,7 +37,7 @@ export function loadOrganization(): ThunkResult { }; } -export function updateOrganization() { +export function updateOrganization(): ThunkResult { return async (dispatch, getStore) => { const organization = getStore().organization.organization; diff --git a/public/app/features/panel/panel_ctrl.ts b/public/app/features/panel/panel_ctrl.ts index e81312aa0de2..cf110cdc705b 100644 --- a/public/app/features/panel/panel_ctrl.ts +++ b/public/app/features/panel/panel_ctrl.ts @@ -60,7 +60,7 @@ export class PanelCtrl { } renderingCompleted() { - profiler.renderingCompleted(this.panel.id); + profiler.renderingCompleted(); } refresh() { diff --git a/public/app/plugins/datasource/prometheus/datasource.ts b/public/app/plugins/datasource/prometheus/datasource.ts index c80c30fc6827..1bd2ffb5d060 100644 --- a/public/app/plugins/datasource/prometheus/datasource.ts +++ b/public/app/plugins/datasource/prometheus/datasource.ts @@ -137,7 +137,7 @@ export class PrometheusDatasource extends DataSourceApi return escapedValues.join('|'); } - targetContainsTemplate(target) { + targetContainsTemplate(target: PromQuery) { return this.templateSrv.variableExists(target.expr); } diff --git a/public/app/types/alerting.ts b/public/app/types/alerting.ts index c987c2d38ede..26516a052ab4 100644 --- a/public/app/types/alerting.ts +++ b/public/app/types/alerting.ts @@ -8,7 +8,7 @@ export interface AlertRuleDTO { state: string; newStateDate: string; evalDate: string; - evalData?: object; + evalData?: { noData?: boolean; evalMatches?: any }; executionError: string; url: string; } @@ -26,7 +26,7 @@ export interface AlertRule { url: string; info?: string; executionError?: string; - evalData?: { noData: boolean }; + evalData?: { noData?: boolean; evalMatches?: any }; } export interface AlertRulesState { diff --git a/scripts/ci-frontend-metrics.sh b/scripts/ci-frontend-metrics.sh index e1bcc3a0031a..c39cf7cf7dac 100755 --- a/scripts/ci-frontend-metrics.sh +++ b/scripts/ci-frontend-metrics.sh @@ -2,7 +2,7 @@ echo -e "Collecting code stats (typescript errors & more)" -ERROR_COUNT_LIMIT=5386 +ERROR_COUNT_LIMIT=5150 DIRECTIVES_LIMIT=172 CONTROLLERS_LIMIT=139 diff --git a/yarn.lock b/yarn.lock index 624f08d556b8..d78a984dd926 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2219,6 +2219,14 @@ "@types/minimatch" "*" "@types/node" "*" +"@types/hoist-non-react-statics@^3.3.0": + version "3.3.1" + resolved "https://registry.yarnpkg.com/@types/hoist-non-react-statics/-/hoist-non-react-statics-3.3.1.tgz#1124aafe5118cb591977aeb1ceaaed1070eb039f" + integrity sha512-iMIqiko6ooLrTh1joXodJK5X9xeEALT1kM5G3ZLhD3hszxBdIEd5C75U834D9mLcINgD4OyZf5uQXjkuYydWvA== + dependencies: + "@types/react" "*" + hoist-non-react-statics "^3.3.0" + "@types/inquirer@0.0.43": version "0.0.43" resolved "https://registry.yarnpkg.com/@types/inquirer/-/inquirer-0.0.43.tgz#1eb0bbb4648e6cc568bd396c1e989f620ad01273" @@ -2384,6 +2392,15 @@ dependencies: "@types/react" "*" +"@types/react-redux@^7.0.8": + version "7.0.8" + resolved "https://registry.yarnpkg.com/@types/react-redux/-/react-redux-7.0.8.tgz#c928863058e334d41031c6bedd0f113bc514e234" + integrity sha512-vIBC15E84ehN6RzdGwRVa41whp9e4CkfPm+WfD0r6y6vqBf4tQPKZeKEBfLLM8k79uSwQC7rh3rH/MFaN1IESQ== + dependencies: + "@types/hoist-non-react-statics" "^3.3.0" + "@types/react" "*" + redux "^4.0.0" + "@types/react-select@2.0.15": version "2.0.15" resolved "https://registry.yarnpkg.com/@types/react-select/-/react-select-2.0.15.tgz#51d607667f59a12e980abcc5bbf9636307293e44" @@ -14671,7 +14688,7 @@ redux-thunk@2.3.0: resolved "https://registry.yarnpkg.com/redux-thunk/-/redux-thunk-2.3.0.tgz#51c2c19a185ed5187aaa9a2d08b666d0d6467622" integrity sha512-km6dclyFnmcvxhAcrQV2AkZmPQjzPDjgVlQtR0EQjxZPyJ0BnMf3in1ryuR8A2qU0HldVRfxYXbFSKlI3N7Slw== -redux@4.0.1: +redux@4.0.1, redux@^4.0.0: version "4.0.1" resolved "https://registry.yarnpkg.com/redux/-/redux-4.0.1.tgz#436cae6cc40fbe4727689d7c8fae44808f1bfef5" integrity sha512-R7bAtSkk7nY6O/OYMVR9RiBI+XghjF9rlbl5806HJbQph0LJVHZrU5oaO4q70eUKiqMRqm4y07KLTlMZ2BlVmg== From bf5b60f74a72433f98acecc526ec12a0e1df718e Mon Sep 17 00:00:00 2001 From: David Date: Mon, 13 May 2019 09:55:20 +0200 Subject: [PATCH 008/166] fix(explore): Prevent double querying for Prometheus and Loki (#17004) * fix(explore): Prevent double querying for Prometheus and Loki - queries were triggered twice because two Enter handlers existed - removed runner plugin from Loki and Prom query fields (runner plugin is still being used in azure) Part of #16995 * Set loki's mtrics capability to false Loki is not a metrics store. Explore was using the `metrics` field in the plugin definition to issue a second query run. But Loki shows only one result viewer. Fixes #16995 --- public/app/features/explore/QueryField.tsx | 6 ++++-- .../datasource/loki/components/LokiQueryFieldForm.tsx | 5 ----- public/app/plugins/datasource/loki/plugin.json | 2 +- .../datasource/prometheus/components/PromQueryField.tsx | 2 -- 4 files changed, 5 insertions(+), 10 deletions(-) diff --git a/public/app/features/explore/QueryField.tsx b/public/app/features/explore/QueryField.tsx index e5d7ff436313..d2a5d04e0d44 100644 --- a/public/app/features/explore/QueryField.tsx +++ b/public/app/features/explore/QueryField.tsx @@ -329,11 +329,13 @@ export class QueryField extends React.PureComponent { diff --git a/public/app/plugins/datasource/loki/components/LokiQueryFieldForm.tsx b/public/app/plugins/datasource/loki/components/LokiQueryFieldForm.tsx index 76e94904c1f3..210d2acb4ccc 100644 --- a/public/app/plugins/datasource/loki/components/LokiQueryFieldForm.tsx +++ b/public/app/plugins/datasource/loki/components/LokiQueryFieldForm.tsx @@ -12,7 +12,6 @@ import QueryField, { TypeaheadInput, QueryFieldState } from 'app/features/explor // dom also includes Element polyfills import { getNextCharacter, getPreviousCousin } from 'app/features/explore/utils/dom'; import BracesPlugin from 'app/features/explore/slate-plugins/braces'; -import RunnerPlugin from 'app/features/explore/slate-plugins/runner'; // Types import { LokiQuery } from '../types'; @@ -77,7 +76,6 @@ export interface LokiQueryFieldFormProps extends ExploreQueryFieldProps { plugins: any[]; - pluginsSearch: any[]; modifiedSearch: string; modifiedQuery: string; @@ -86,14 +84,11 @@ export class LokiQueryFieldForm extends React.PureComponent node.type === 'code_block', getSyntax: (node: any) => 'promql', }), ]; - - this.pluginsSearch = [RunnerPlugin({ handler: props.onRunQuery })]; } loadOptions = (selectedOptions: CascaderOption[]) => { diff --git a/public/app/plugins/datasource/loki/plugin.json b/public/app/plugins/datasource/loki/plugin.json index 66e0f1027e9e..cd14a7fe48ad 100644 --- a/public/app/plugins/datasource/loki/plugin.json +++ b/public/app/plugins/datasource/loki/plugin.json @@ -4,7 +4,7 @@ "id": "loki", "category": "logging", - "metrics": true, + "metrics": false, "alerting": false, "annotations": false, "logs": true, diff --git a/public/app/plugins/datasource/prometheus/components/PromQueryField.tsx b/public/app/plugins/datasource/prometheus/components/PromQueryField.tsx index a63e2ef52b97..14d03df6d388 100644 --- a/public/app/plugins/datasource/prometheus/components/PromQueryField.tsx +++ b/public/app/plugins/datasource/prometheus/components/PromQueryField.tsx @@ -12,7 +12,6 @@ import { TypeaheadOutput, HistoryItem } from 'app/types/explore'; // dom also includes Element polyfills import { getNextCharacter, getPreviousCousin } from 'app/features/explore/utils/dom'; import BracesPlugin from 'app/features/explore/slate-plugins/braces'; -import RunnerPlugin from 'app/features/explore/slate-plugins/runner'; import QueryField, { TypeaheadInput, QueryFieldState } from 'app/features/explore/QueryField'; import { PromQuery } from '../types'; import { CancelablePromise, makePromiseCancelable } from 'app/core/utils/CancelablePromise'; @@ -126,7 +125,6 @@ class PromQueryField extends React.PureComponent node.type === 'code_block', getSyntax: (node: any) => 'promql', From 927e1cbd27888b5e4e913862bf820909dcd3fb6a Mon Sep 17 00:00:00 2001 From: David Date: Mon, 13 May 2019 09:58:26 +0200 Subject: [PATCH 009/166] (feat/explore): Support for new LogQL filtering syntax (#16674) * (feat/explore): Support for new LogQL filtering syntax Loki is adding syntax to support chained filtering. This PR adapts Grafana to support this. - Send only `query` parameter in loki request - Automatically wrap search text in simple syntax, e.g., `{} foo` is sent as `{} |~ "foo"`. * Adapted to regexp parameter staying on in Loki * Dont wrap single regexp in new filter syntax * Fix datasource test * Fallback regexp parameter for legacy queries * Fix search highlighting * Make highlighting work for filter chains * Fix datasource test --- packages/grafana-ui/src/types/data.ts | 2 +- packages/grafana-ui/src/types/datasource.ts | 2 +- public/app/core/logs_model.ts | 4 +- public/app/core/utils/text.ts | 2 +- public/app/features/explore/LogRow.tsx | 2 +- public/app/features/explore/QueryRow.tsx | 2 +- .../datasource/loki/datasource.test.ts | 4 +- .../app/plugins/datasource/loki/datasource.ts | 17 +++-- .../datasource/loki/query_utils.test.ts | 53 +++++++++++---- .../plugins/datasource/loki/query_utils.ts | 64 ++++++++++++++++--- public/app/plugins/datasource/loki/types.ts | 5 ++ 11 files changed, 122 insertions(+), 35 deletions(-) diff --git a/packages/grafana-ui/src/types/data.ts b/packages/grafana-ui/src/types/data.ts index 678efc40f007..e629e76043a7 100644 --- a/packages/grafana-ui/src/types/data.ts +++ b/packages/grafana-ui/src/types/data.ts @@ -21,7 +21,7 @@ export interface QueryResultMeta { requestId?: string; // Used in Explore for highlighting - search?: string; + searchWords?: string[]; // Used in Explore to show limit applied to search result limit?: number; diff --git a/packages/grafana-ui/src/types/datasource.ts b/packages/grafana-ui/src/types/datasource.ts index 3be0bae09dd8..2b40064d7d9d 100644 --- a/packages/grafana-ui/src/types/datasource.ts +++ b/packages/grafana-ui/src/types/datasource.ts @@ -194,7 +194,7 @@ export abstract class ExploreDataSourceApi< TOptions extends DataSourceJsonData = DataSourceJsonData > extends DataSourceApi { modifyQuery?(query: TQuery, action: QueryFixAction): TQuery; - getHighlighterExpression?(query: TQuery): string; + getHighlighterExpression?(query: TQuery): string[]; languageProvider?: any; } diff --git a/public/app/core/logs_model.ts b/public/app/core/logs_model.ts index eb292c033f8a..fd7e5c638a94 100644 --- a/public/app/core/logs_model.ts +++ b/public/app/core/logs_model.ts @@ -446,7 +446,7 @@ export function processLogSeriesRow( const timeLocal = time.format('YYYY-MM-DD HH:mm:ss'); const logLevel = getLogLevel(message); const hasAnsi = hasAnsiCodes(message); - const search = series.meta && series.meta.search ? series.meta.search : ''; + const searchWords = series.meta && series.meta.searchWords ? series.meta.searchWords : []; return { logLevel, @@ -455,10 +455,10 @@ export function processLogSeriesRow( timeLocal, uniqueLabels, hasAnsi, + searchWords, entry: hasAnsi ? ansicolor.strip(message) : message, raw: message, labels: series.labels, - searchWords: search ? [search] : [], timestamp: ts, }; } diff --git a/public/app/core/utils/text.ts b/public/app/core/utils/text.ts index faf801b45be8..6db844e736ef 100644 --- a/public/app/core/utils/text.ts +++ b/public/app/core/utils/text.ts @@ -6,7 +6,7 @@ import xss from 'xss'; * See https://github.com/bvaughn/react-highlight-words#props */ export function findHighlightChunksInText({ searchWords, textToHighlight }) { - return findMatchesInText(textToHighlight, searchWords.join(' ')); + return searchWords.reduce((acc, term) => [...acc, ...findMatchesInText(textToHighlight, term)], []); } const cleanNeedle = (needle: string): string => { diff --git a/public/app/features/explore/LogRow.tsx b/public/app/features/explore/LogRow.tsx index 19930a8a3393..8e3de04749b8 100644 --- a/public/app/features/explore/LogRow.tsx +++ b/public/app/features/explore/LogRow.tsx @@ -133,7 +133,7 @@ export class LogRow extends PureComponent { const { entry, hasAnsi, raw } = row; const previewHighlights = highlighterExpressions && !_.isEqual(highlighterExpressions, row.searchWords); const highlights = previewHighlights ? highlighterExpressions : row.searchWords; - const needsHighlighter = highlights && highlights.length > 0 && highlights[0].length > 0; + const needsHighlighter = highlights && highlights.length > 0 && highlights[0] && highlights[0].length > 0; const highlightClassName = classnames('logs-row__match-highlight', { 'logs-row__match-highlight--preview': previewHighlights, }); diff --git a/public/app/features/explore/QueryRow.tsx b/public/app/features/explore/QueryRow.tsx index 06034ecdbfff..fc4a5e025e94 100644 --- a/public/app/features/explore/QueryRow.tsx +++ b/public/app/features/explore/QueryRow.tsx @@ -98,7 +98,7 @@ export class QueryRow extends PureComponent { const { datasourceInstance } = this.props; if (datasourceInstance.getHighlighterExpression) { const { exploreId } = this.props; - const expressions = [datasourceInstance.getHighlighterExpression(value)]; + const expressions = datasourceInstance.getHighlighterExpression(value); this.props.highlightLogsExpressionAction({ exploreId, expressions }); } }, 500); diff --git a/public/app/plugins/datasource/loki/datasource.test.ts b/public/app/plugins/datasource/loki/datasource.test.ts index 8b970f05f63e..8200cf0f4a14 100644 --- a/public/app/plugins/datasource/loki/datasource.test.ts +++ b/public/app/plugins/datasource/loki/datasource.test.ts @@ -61,7 +61,7 @@ describe('LokiDatasource', () => { backendSrvMock.datasourceRequest = jest.fn(() => Promise.resolve(testResp)); const options = getQueryOptions({ - targets: [{ expr: 'foo', refId: 'B' }], + targets: [{ expr: '{} foo', refId: 'B' }], }); const res = await ds.query(options); @@ -69,7 +69,7 @@ describe('LokiDatasource', () => { const seriesData = res.data[0] as SeriesData; expect(seriesData.rows[0][1]).toBe('hello'); expect(seriesData.meta.limit).toBe(20); - expect(seriesData.meta.search).toBe('(?i)foo'); + expect(seriesData.meta.searchWords).toEqual(['(?i)foo']); done(); }); }); diff --git a/public/app/plugins/datasource/loki/datasource.ts b/public/app/plugins/datasource/loki/datasource.ts index 3e7e5f3b3968..04f846584911 100644 --- a/public/app/plugins/datasource/loki/datasource.ts +++ b/public/app/plugins/datasource/loki/datasource.ts @@ -6,7 +6,7 @@ import * as dateMath from '@grafana/ui/src/utils/datemath'; import { addLabelToSelector } from 'app/plugins/datasource/prometheus/add_label_to_query'; import LanguageProvider from './language_provider'; import { logStreamToSeriesData } from './result_transformer'; -import { formatQuery, parseQuery } from './query_utils'; +import { formatQuery, parseQuery, getHighlighterExpressionsFromQuery } from './query_utils'; // Types import { @@ -69,12 +69,14 @@ export class LokiDatasource extends DataSourceApi { prepareQueryTarget(target: LokiQuery, options: DataQueryRequest) { const interpolated = this.templateSrv.replace(target.expr); + const { query, regexp } = parseQuery(interpolated); const start = this.getTime(options.range.from, false); const end = this.getTime(options.range.to, true); const refId = target.refId; return { ...DEFAULT_QUERY_PARAMS, - ...parseQuery(interpolated), + query, + regexp, start, end, limit: this.maxLines, @@ -126,14 +128,15 @@ export class LokiDatasource extends DataSourceApi { for (let i = 0; i < results.length; i++) { const result = results[i]; - if (result.data) { const refId = queryTargets[i].refId; for (const stream of result.data.streams || []) { const seriesData = logStreamToSeriesData(stream); seriesData.refId = refId; seriesData.meta = { - search: queryTargets[i].regexp, + searchWords: getHighlighterExpressionsFromQuery( + formatQuery(queryTargets[i].query, queryTargets[i].regexp) + ), limit: this.maxLines, }; series.push(seriesData); @@ -160,7 +163,7 @@ export class LokiDatasource extends DataSourceApi { modifyQuery(query: LokiQuery, action: any): LokiQuery { const parsed = parseQuery(query.expr || ''); - let selector = parsed.query; + let { query: selector } = parsed; switch (action.type) { case 'ADD_FILTER': { selector = addLabelToSelector(selector, action.key, action.value); @@ -173,8 +176,8 @@ export class LokiDatasource extends DataSourceApi { return { ...query, expr: expression }; } - getHighlighterExpression(query: LokiQuery): string { - return parseQuery(query.expr).regexp; + getHighlighterExpression(query: LokiQuery): string[] { + return getHighlighterExpressionsFromQuery(query.expr); } getTime(date, roundUp) { diff --git a/public/app/plugins/datasource/loki/query_utils.test.ts b/public/app/plugins/datasource/loki/query_utils.test.ts index 3685a3dd358e..964f8678a795 100644 --- a/public/app/plugins/datasource/loki/query_utils.test.ts +++ b/public/app/plugins/datasource/loki/query_utils.test.ts @@ -1,56 +1,87 @@ -import { parseQuery } from './query_utils'; +import { parseQuery, getHighlighterExpressionsFromQuery } from './query_utils'; +import { LokiExpression } from './types'; describe('parseQuery', () => { it('returns empty for empty string', () => { expect(parseQuery('')).toEqual({ query: '', regexp: '', - }); + } as LokiExpression); }); it('returns regexp for strings without query', () => { expect(parseQuery('test')).toEqual({ - query: '', - regexp: '(?i)test', - }); + query: 'test', + regexp: '', + } as LokiExpression); }); it('returns query for strings without regexp', () => { expect(parseQuery('{foo="bar"}')).toEqual({ query: '{foo="bar"}', regexp: '', - }); + } as LokiExpression); }); it('returns query for strings with query and search string', () => { expect(parseQuery('x {foo="bar"}')).toEqual({ query: '{foo="bar"}', regexp: '(?i)x', - }); + } as LokiExpression); }); it('returns query for strings with query and regexp', () => { expect(parseQuery('{foo="bar"} x|y')).toEqual({ query: '{foo="bar"}', regexp: '(?i)x|y', - }); + } as LokiExpression); }); it('returns query for selector with two labels', () => { expect(parseQuery('{foo="bar", baz="42"}')).toEqual({ query: '{foo="bar", baz="42"}', regexp: '', - }); + } as LokiExpression); }); it('returns query and regexp with quantifiers', () => { expect(parseQuery('{foo="bar"} \\.java:[0-9]{1,5}')).toEqual({ query: '{foo="bar"}', regexp: '(?i)\\.java:[0-9]{1,5}', - }); + } as LokiExpression); expect(parseQuery('\\.java:[0-9]{1,5} {foo="bar"}')).toEqual({ query: '{foo="bar"}', regexp: '(?i)\\.java:[0-9]{1,5}', - }); + } as LokiExpression); + }); + + it('returns query with filter operands as is', () => { + expect(parseQuery('{foo="bar"} |= "x|y"')).toEqual({ + query: '{foo="bar"} |= "x|y"', + regexp: '', + } as LokiExpression); + expect(parseQuery('{foo="bar"} |~ "42"')).toEqual({ + query: '{foo="bar"} |~ "42"', + regexp: '', + } as LokiExpression); + }); +}); + +describe('getHighlighterExpressionsFromQuery', () => { + it('returns no expressions for empty query', () => { + expect(getHighlighterExpressionsFromQuery('')).toEqual([]); + }); + it('returns a single expressions for legacy query', () => { + expect(getHighlighterExpressionsFromQuery('{} x')).toEqual(['(?i)x']); + expect(getHighlighterExpressionsFromQuery('{foo="bar"} x')).toEqual(['(?i)x']); + }); + it('returns an expression for query with filter', () => { + expect(getHighlighterExpressionsFromQuery('{foo="bar"} |= "x"')).toEqual(['x']); + }); + it('returns expressions for query with filter chain', () => { + expect(getHighlighterExpressionsFromQuery('{foo="bar"} |= "x" |~ "y"')).toEqual(['x', 'y']); + }); + it('returns drops expressions for query with negative filter chain', () => { + expect(getHighlighterExpressionsFromQuery('{foo="bar"} |= "x" != "y"')).toEqual(['x']); }); }); diff --git a/public/app/plugins/datasource/loki/query_utils.ts b/public/app/plugins/datasource/loki/query_utils.ts index 7d2c6234f050..54fcca8809a3 100644 --- a/public/app/plugins/datasource/loki/query_utils.ts +++ b/public/app/plugins/datasource/loki/query_utils.ts @@ -1,22 +1,70 @@ +import { LokiExpression } from './types'; + const selectorRegexp = /(?:^|\s){[^{]*}/g; const caseInsensitive = '(?i)'; // Golang mode modifier for Loki, doesn't work in JavaScript -export function parseQuery(input: string) { +export function parseQuery(input: string): LokiExpression { input = input || ''; const match = input.match(selectorRegexp); - let query = ''; - let regexp = input; + let query = input; + let regexp = ''; if (match) { - query = match[0].trim(); regexp = input.replace(selectorRegexp, '').trim(); + // Keep old-style regexp, otherwise take whole query + if (regexp && regexp.search(/\|=|\|~|!=|!~/) === -1) { + query = match[0].trim(); + if (!regexp.startsWith(caseInsensitive)) { + regexp = `${caseInsensitive}${regexp}`; + } + } else { + regexp = ''; + } } - if (regexp) { - regexp = caseInsensitive + regexp; - } - return { query, regexp }; + return { regexp, query }; } export function formatQuery(selector: string, search: string): string { return `${selector || ''} ${search || ''}`.trim(); } + +/** + * Returns search terms from a LogQL query. + * E.g., `{} |= foo |=bar != baz` returns `['foo', 'bar']`. + */ +export function getHighlighterExpressionsFromQuery(input: string): string[] { + const parsed = parseQuery(input); + // Legacy syntax + if (parsed.regexp) { + return [parsed.regexp]; + } + let expression = input; + const results = []; + // Consume filter expression from left to right + while (expression) { + const filterStart = expression.search(/\|=|\|~|!=|!~/); + // Nothing more to search + if (filterStart === -1) { + break; + } + // Drop terms for negative filters + const skip = expression.substr(filterStart).search(/!=|!~/) === 0; + expression = expression.substr(filterStart + 2); + if (skip) { + continue; + } + // Check if there is more chained + const filterEnd = expression.search(/\|=|\|~|!=|!~/); + let filterTerm; + if (filterEnd === -1) { + filterTerm = expression.trim(); + } else { + filterTerm = expression.substr(0, filterEnd); + expression = expression.substr(filterEnd); + } + + // Unwrap the filter term by removing quotes + results.push(filterTerm.replace(/^\s*"/g, '').replace(/"\s*$/g, '')); + } + return results; +} diff --git a/public/app/plugins/datasource/loki/types.ts b/public/app/plugins/datasource/loki/types.ts index c4cfa3fcdc43..4c973f8a79ed 100644 --- a/public/app/plugins/datasource/loki/types.ts +++ b/public/app/plugins/datasource/loki/types.ts @@ -22,3 +22,8 @@ export interface LokiLogsStreamEntry { // Legacy, was renamed to ts timestamp?: string; } + +export interface LokiExpression { + regexp: string; + query: string; +} From db95414d02a4c2bc54f8759abc351c9af53a7b5c Mon Sep 17 00:00:00 2001 From: Oleg Gaidarenko Date: Mon, 13 May 2019 11:51:16 +0300 Subject: [PATCH 010/166] Feature: provide multildap server configuration (#16914) * Feature: provide multildap server configuration * Add multildap server configuration for devenv * Change some of the notes for openldap devenv configuration * Change the maintainer label for *main* dockerfile and of the devenv one Re-checked the multildap logic - everything seems to be working fine --- Dockerfile | 2 + .../admins-ldap-server/Dockerfile | 30 ++++++ .../admins-ldap-server/modules/memberof.ldif | 33 +++++++ .../prepopulate/1_units.ldif | 9 ++ .../prepopulate/2_users.ldif | 20 ++++ .../prepopulate/3_groups.ldif | 6 ++ .../multiple-openldap/docker-compose.yaml | 19 ++++ .../blocks/multiple-openldap/entrypoint.sh | 98 +++++++++++++++++++ .../multiple-openldap/ldap-server/Dockerfile | 30 ++++++ .../ldap-server/modules/memberof.ldif | 33 +++++++ .../ldap-server/prepopulate/1_units.ldif | 9 ++ .../ldap-server/prepopulate/2_users.ldif | 59 +++++++++++ .../ldap-server/prepopulate/3_groups.ldif | 23 +++++ .../blocks/multiple-openldap/ldap_dev.toml | 59 +++++++++++ .../docker/blocks/multiple-openldap/notes.md | 38 +++++++ .../blocks/multiple-openldap/prepopulate.sh | 14 +++ devenv/docker/blocks/openldap/Dockerfile | 2 +- devenv/docker/blocks/openldap/notes.md | 5 +- 18 files changed, 484 insertions(+), 5 deletions(-) create mode 100644 devenv/docker/blocks/multiple-openldap/admins-ldap-server/Dockerfile create mode 100644 devenv/docker/blocks/multiple-openldap/admins-ldap-server/modules/memberof.ldif create mode 100644 devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/1_units.ldif create mode 100644 devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/2_users.ldif create mode 100644 devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/3_groups.ldif create mode 100644 devenv/docker/blocks/multiple-openldap/docker-compose.yaml create mode 100755 devenv/docker/blocks/multiple-openldap/entrypoint.sh create mode 100644 devenv/docker/blocks/multiple-openldap/ldap-server/Dockerfile create mode 100644 devenv/docker/blocks/multiple-openldap/ldap-server/modules/memberof.ldif create mode 100644 devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/1_units.ldif create mode 100644 devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/2_users.ldif create mode 100644 devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/3_groups.ldif create mode 100644 devenv/docker/blocks/multiple-openldap/ldap_dev.toml create mode 100644 devenv/docker/blocks/multiple-openldap/notes.md create mode 100755 devenv/docker/blocks/multiple-openldap/prepopulate.sh diff --git a/Dockerfile b/Dockerfile index 537aaca840cb..fd305d8af3ee 100644 --- a/Dockerfile +++ b/Dockerfile @@ -35,6 +35,8 @@ RUN ./node_modules/.bin/grunt build # Final container FROM debian:stretch-slim +LABEL maintainer="Grafana team " + ARG GF_UID="472" ARG GF_GID="472" diff --git a/devenv/docker/blocks/multiple-openldap/admins-ldap-server/Dockerfile b/devenv/docker/blocks/multiple-openldap/admins-ldap-server/Dockerfile new file mode 100644 index 000000000000..979d01c7dad4 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/admins-ldap-server/Dockerfile @@ -0,0 +1,30 @@ +# Fork of https://github.com/dinkel/docker-openldap + +FROM debian:jessie + +LABEL maintainer="Grafana team " + +ENV OPENLDAP_VERSION 2.4.40 + +RUN apt-get update && \ + DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -y \ + slapd=${OPENLDAP_VERSION}* \ + ldap-utils && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + +RUN mv /etc/ldap /etc/ldap.dist + +EXPOSE 389 + +VOLUME ["/etc/ldap", "/var/lib/ldap"] + +COPY modules/ /etc/ldap.dist/modules +COPY prepopulate/ /etc/ldap.dist/prepopulate + +COPY ../entrypoint.sh /entrypoint.sh +COPY ../prepopulate.sh /prepopulate.sh + +ENTRYPOINT ["/entrypoint.sh"] + +CMD ["slapd", "-d", "32768", "-u", "openldap", "-g", "openldap"] diff --git a/devenv/docker/blocks/multiple-openldap/admins-ldap-server/modules/memberof.ldif b/devenv/docker/blocks/multiple-openldap/admins-ldap-server/modules/memberof.ldif new file mode 100644 index 000000000000..fd9cce957c33 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/admins-ldap-server/modules/memberof.ldif @@ -0,0 +1,33 @@ +dn: cn=module,cn=config +cn: module +objectClass: olcModuleList +objectClass: top +olcModulePath: /usr/lib/ldap +olcModuleLoad: memberof.la + +dn: olcOverlay={0}memberof,olcDatabase={1}hdb,cn=config +objectClass: olcConfig +objectClass: olcMemberOf +objectClass: olcOverlayConfig +objectClass: top +olcOverlay: memberof +olcMemberOfDangling: ignore +olcMemberOfRefInt: TRUE +olcMemberOfGroupOC: groupOfNames +olcMemberOfMemberAD: member +olcMemberOfMemberOfAD: memberOf + +dn: cn=module,cn=config +cn: module +objectClass: olcModuleList +objectClass: top +olcModulePath: /usr/lib/ldap +olcModuleLoad: refint.la + +dn: olcOverlay={1}refint,olcDatabase={1}hdb,cn=config +objectClass: olcConfig +objectClass: olcOverlayConfig +objectClass: olcRefintConfig +objectClass: top +olcOverlay: {1}refint +olcRefintAttribute: memberof member manager owner diff --git a/devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/1_units.ldif b/devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/1_units.ldif new file mode 100644 index 000000000000..22e063036889 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/1_units.ldif @@ -0,0 +1,9 @@ +dn: ou=groups,dc=grafana,dc=org +ou: Groups +objectclass: top +objectclass: organizationalUnit + +dn: ou=users,dc=grafana,dc=org +ou: Users +objectclass: top +objectclass: organizationalUnit diff --git a/devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/2_users.ldif b/devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/2_users.ldif new file mode 100644 index 000000000000..1ee592dc7a06 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/2_users.ldif @@ -0,0 +1,20 @@ +# ldap-admin +dn: cn=ldap-admin,ou=users,dc=grafana,dc=org +mail: ldap-admin@grafana.com +userPassword: grafana +objectClass: person +objectClass: top +objectClass: inetOrgPerson +objectClass: organizationalPerson +sn: ldap-admin +cn: ldap-admin + +dn: cn=ldap-torkel,ou=users,dc=grafana,dc=org +mail: ldap-torkel@grafana.com +userPassword: grafana +objectClass: person +objectClass: top +objectClass: inetOrgPerson +objectClass: organizationalPerson +sn: ldap-torkel +cn: ldap-torkel diff --git a/devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/3_groups.ldif b/devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/3_groups.ldif new file mode 100644 index 000000000000..f7285f8a9c32 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/admins-ldap-server/prepopulate/3_groups.ldif @@ -0,0 +1,6 @@ +dn: cn=admins,ou=groups,dc=grafana,dc=org +cn: admins +objectClass: groupOfNames +objectClass: top +member: cn=ldap-admin,ou=users,dc=grafana,dc=org +member: cn=ldap-torkel,ou=users,dc=grafana,dc=org diff --git a/devenv/docker/blocks/multiple-openldap/docker-compose.yaml b/devenv/docker/blocks/multiple-openldap/docker-compose.yaml new file mode 100644 index 000000000000..74f5d29a90ff --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/docker-compose.yaml @@ -0,0 +1,19 @@ + admins-openldap: + build: docker/blocks/multiple-openldap/admins-ldap-server + environment: + SLAPD_PASSWORD: grafana + SLAPD_DOMAIN: grafana.org + SLAPD_ADDITIONAL_MODULES: memberof + ports: + - "389:389" + + openldap: + build: docker/blocks/multiple-openldap/ldap-server + environment: + SLAPD_PASSWORD: grafana + SLAPD_DOMAIN: grafana.org + SLAPD_ADDITIONAL_MODULES: memberof + ports: + - "388:389" + + diff --git a/devenv/docker/blocks/multiple-openldap/entrypoint.sh b/devenv/docker/blocks/multiple-openldap/entrypoint.sh new file mode 100755 index 000000000000..d202ed14b31f --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/entrypoint.sh @@ -0,0 +1,98 @@ +#!/bin/bash + +# When not limiting the open file descritors limit, the memory consumption of +# slapd is absurdly high. See https://github.com/docker/docker/issues/8231 +ulimit -n 8192 + + +set -e + +chown -R openldap:openldap /var/lib/ldap/ + +if [[ ! -d /etc/ldap/slapd.d ]]; then + + if [[ -z "$SLAPD_PASSWORD" ]]; then + echo -n >&2 "Error: Container not configured and SLAPD_PASSWORD not set. " + echo >&2 "Did you forget to add -e SLAPD_PASSWORD=... ?" + exit 1 + fi + + if [[ -z "$SLAPD_DOMAIN" ]]; then + echo -n >&2 "Error: Container not configured and SLAPD_DOMAIN not set. " + echo >&2 "Did you forget to add -e SLAPD_DOMAIN=... ?" + exit 1 + fi + + SLAPD_ORGANIZATION="${SLAPD_ORGANIZATION:-${SLAPD_DOMAIN}}" + + cp -a /etc/ldap.dist/* /etc/ldap + + cat <<-EOF | debconf-set-selections + slapd slapd/no_configuration boolean false + slapd slapd/password1 password $SLAPD_PASSWORD + slapd slapd/password2 password $SLAPD_PASSWORD + slapd shared/organization string $SLAPD_ORGANIZATION + slapd slapd/domain string $SLAPD_DOMAIN + slapd slapd/backend select HDB + slapd slapd/allow_ldap_v2 boolean false + slapd slapd/purge_database boolean false + slapd slapd/move_old_database boolean true +EOF + + dpkg-reconfigure -f noninteractive slapd >/dev/null 2>&1 + + dc_string="" + + IFS="."; declare -a dc_parts=($SLAPD_DOMAIN) + + for dc_part in "${dc_parts[@]}"; do + dc_string="$dc_string,dc=$dc_part" + done + + base_string="BASE ${dc_string:1}" + + sed -i "s/^#BASE.*/${base_string}/g" /etc/ldap/ldap.conf + + if [[ -n "$SLAPD_CONFIG_PASSWORD" ]]; then + password_hash=`slappasswd -s "${SLAPD_CONFIG_PASSWORD}"` + + sed_safe_password_hash=${password_hash//\//\\\/} + + slapcat -n0 -F /etc/ldap/slapd.d -l /tmp/config.ldif + sed -i "s/\(olcRootDN: cn=admin,cn=config\)/\1\nolcRootPW: ${sed_safe_password_hash}/g" /tmp/config.ldif + rm -rf /etc/ldap/slapd.d/* + slapadd -n0 -F /etc/ldap/slapd.d -l /tmp/config.ldif >/dev/null 2>&1 + fi + + if [[ -n "$SLAPD_ADDITIONAL_SCHEMAS" ]]; then + IFS=","; declare -a schemas=($SLAPD_ADDITIONAL_SCHEMAS); unset IFS + + for schema in "${schemas[@]}"; do + slapadd -n0 -F /etc/ldap/slapd.d -l "/etc/ldap/schema/${schema}.ldif" >/dev/null 2>&1 + done + fi + + if [[ -n "$SLAPD_ADDITIONAL_MODULES" ]]; then + IFS=","; declare -a modules=($SLAPD_ADDITIONAL_MODULES); unset IFS + + for module in "${modules[@]}"; do + echo "Adding module ${module}" + slapadd -n0 -F /etc/ldap/slapd.d -l "/etc/ldap/modules/${module}.ldif" >/dev/null 2>&1 + done + fi + + # This needs to run in background + # Will prepopulate entries after ldap daemon has started + ./prepopulate.sh & + + chown -R openldap:openldap /etc/ldap/slapd.d/ /var/lib/ldap/ /var/run/slapd/ +else + slapd_configs_in_env=`env | grep 'SLAPD_'` + + if [ -n "${slapd_configs_in_env:+x}" ]; then + echo "Info: Container already configured, therefore ignoring SLAPD_xxx environment variables" + fi +fi + +exec "$@" + diff --git a/devenv/docker/blocks/multiple-openldap/ldap-server/Dockerfile b/devenv/docker/blocks/multiple-openldap/ldap-server/Dockerfile new file mode 100644 index 000000000000..979d01c7dad4 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/ldap-server/Dockerfile @@ -0,0 +1,30 @@ +# Fork of https://github.com/dinkel/docker-openldap + +FROM debian:jessie + +LABEL maintainer="Grafana team " + +ENV OPENLDAP_VERSION 2.4.40 + +RUN apt-get update && \ + DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -y \ + slapd=${OPENLDAP_VERSION}* \ + ldap-utils && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists/* + +RUN mv /etc/ldap /etc/ldap.dist + +EXPOSE 389 + +VOLUME ["/etc/ldap", "/var/lib/ldap"] + +COPY modules/ /etc/ldap.dist/modules +COPY prepopulate/ /etc/ldap.dist/prepopulate + +COPY ../entrypoint.sh /entrypoint.sh +COPY ../prepopulate.sh /prepopulate.sh + +ENTRYPOINT ["/entrypoint.sh"] + +CMD ["slapd", "-d", "32768", "-u", "openldap", "-g", "openldap"] diff --git a/devenv/docker/blocks/multiple-openldap/ldap-server/modules/memberof.ldif b/devenv/docker/blocks/multiple-openldap/ldap-server/modules/memberof.ldif new file mode 100644 index 000000000000..fd9cce957c33 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/ldap-server/modules/memberof.ldif @@ -0,0 +1,33 @@ +dn: cn=module,cn=config +cn: module +objectClass: olcModuleList +objectClass: top +olcModulePath: /usr/lib/ldap +olcModuleLoad: memberof.la + +dn: olcOverlay={0}memberof,olcDatabase={1}hdb,cn=config +objectClass: olcConfig +objectClass: olcMemberOf +objectClass: olcOverlayConfig +objectClass: top +olcOverlay: memberof +olcMemberOfDangling: ignore +olcMemberOfRefInt: TRUE +olcMemberOfGroupOC: groupOfNames +olcMemberOfMemberAD: member +olcMemberOfMemberOfAD: memberOf + +dn: cn=module,cn=config +cn: module +objectClass: olcModuleList +objectClass: top +olcModulePath: /usr/lib/ldap +olcModuleLoad: refint.la + +dn: olcOverlay={1}refint,olcDatabase={1}hdb,cn=config +objectClass: olcConfig +objectClass: olcOverlayConfig +objectClass: olcRefintConfig +objectClass: top +olcOverlay: {1}refint +olcRefintAttribute: memberof member manager owner diff --git a/devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/1_units.ldif b/devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/1_units.ldif new file mode 100644 index 000000000000..22e063036889 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/1_units.ldif @@ -0,0 +1,9 @@ +dn: ou=groups,dc=grafana,dc=org +ou: Groups +objectclass: top +objectclass: organizationalUnit + +dn: ou=users,dc=grafana,dc=org +ou: Users +objectclass: top +objectclass: organizationalUnit diff --git a/devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/2_users.ldif b/devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/2_users.ldif new file mode 100644 index 000000000000..8e1dfbf603ad --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/2_users.ldif @@ -0,0 +1,59 @@ +dn: cn=ldap-editor,ou=users,dc=grafana,dc=org +mail: ldap-editor@grafana.com +userPassword: grafana +objectClass: person +objectClass: top +objectClass: inetOrgPerson +objectClass: organizationalPerson +sn: ldap-editor +cn: ldap-editor + +dn: cn=ldap-viewer,ou=users,dc=grafana,dc=org +mail: ldap-viewer@grafana.com +userPassword: grafana +objectClass: person +objectClass: top +objectClass: inetOrgPerson +objectClass: organizationalPerson +sn: ldap-viewer +cn: ldap-viewer + +dn: cn=ldap-carl,ou=users,dc=grafana,dc=org +mail: ldap-carl@grafana.com +userPassword: grafana +objectClass: person +objectClass: top +objectClass: inetOrgPerson +objectClass: organizationalPerson +sn: ldap-carl +cn: ldap-carl + +dn: cn=ldap-daniel,ou=users,dc=grafana,dc=org +mail: ldap-daniel@grafana.com +userPassword: grafana +objectClass: person +objectClass: top +objectClass: inetOrgPerson +objectClass: organizationalPerson +sn: ldap-daniel +cn: ldap-daniel + +dn: cn=ldap-leo,ou=users,dc=grafana,dc=org +mail: ldap-leo@grafana.com +userPassword: grafana +objectClass: person +objectClass: top +objectClass: inetOrgPerson +objectClass: organizationalPerson +sn: ldap-leo +cn: ldap-leo + +dn: cn=ldap-tobias,ou=users,dc=grafana,dc=org +mail: ldap-tobias@grafana.com +userPassword: grafana +objectClass: person +objectClass: top +objectClass: inetOrgPerson +objectClass: organizationalPerson +sn: ldap-tobias +cn: ldap-tobias diff --git a/devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/3_groups.ldif b/devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/3_groups.ldif new file mode 100644 index 000000000000..8d55eaaa7079 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/ldap-server/prepopulate/3_groups.ldif @@ -0,0 +1,23 @@ +dn: cn=admins,ou=groups,dc=grafana,dc=org +cn: admins +objectClass: groupOfNames +objectClass: top + +dn: cn=editors,ou=groups,dc=grafana,dc=org +cn: editors +objectClass: groupOfNames +member: cn=ldap-editor,ou=users,dc=grafana,dc=org + +dn: cn=backend,ou=groups,dc=grafana,dc=org +cn: backend +objectClass: groupOfNames +member: cn=ldap-carl,ou=users,dc=grafana,dc=org +member: cn=ldap-leo,ou=users,dc=grafana,dc=org +member: cn=ldap-torkel,ou=users,dc=grafana,dc=org + +dn: cn=frontend,ou=groups,dc=grafana,dc=org +cn: frontend +objectClass: groupOfNames +member: cn=ldap-torkel,ou=users,dc=grafana,dc=org +member: cn=ldap-daniel,ou=users,dc=grafana,dc=org +member: cn=ldap-leo,ou=users,dc=grafana,dc=org diff --git a/devenv/docker/blocks/multiple-openldap/ldap_dev.toml b/devenv/docker/blocks/multiple-openldap/ldap_dev.toml new file mode 100644 index 000000000000..c4c2516694f4 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/ldap_dev.toml @@ -0,0 +1,59 @@ +# To troubleshoot and get more log info enable ldap debug logging in grafana.ini +# [log] +# filters = ldap:debug + +# For the verbose comments options see "openldap" env block + +# --- First LDAP Server (only admins) --- + +[[servers]] +host = "127.0.0.1" +port = 389 +use_ssl = false +start_tls = false +ssl_skip_verify = false +bind_dn = "cn=admin,dc=grafana,dc=org" +bind_password = 'grafana' +search_filter = "(cn=%s)" +search_base_dns = ["ou=users,dc=grafana,dc=org"] + +[servers.attributes] +name = "givenName" +surname = "sn" +username = "cn" +member_of = "memberOf" +email = "email" + +[[servers.group_mappings]] +group_dn = "cn=admins,ou=groups,dc=grafana,dc=org" +org_role = "Admin" +grafana_admin = true + +# --- Second LDAP Server (rest of the users) --- + +[[servers]] +host = "127.0.0.1" +port = 388 +use_ssl = false +start_tls = false +ssl_skip_verify = false + +bind_dn = "cn=admin,dc=grafana,dc=org" +bind_password = 'grafana' +search_filter = "(cn=%s)" +search_base_dns = ["ou=users,dc=grafana,dc=org"] + +[servers.attributes] +name = "givenName" +surname = "sn" +username = "cn" +member_of = "memberOf" +email = "email" + +[[servers.group_mappings]] +group_dn = "cn=editors,ou=groups,dc=grafana,dc=org" +org_role = "Editor" + +[[servers.group_mappings]] +group_dn = "*" +org_role = "Viewer" diff --git a/devenv/docker/blocks/multiple-openldap/notes.md b/devenv/docker/blocks/multiple-openldap/notes.md new file mode 100644 index 000000000000..1fcbfa013db0 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/notes.md @@ -0,0 +1,38 @@ +# Notes on Multiple OpenLdap Docker Block + +This is very similar to openldap docker block, but it creates multiple ldap servers instead of one. + +Any ldif files added to the prepopulate subdirectory will be automatically imported into the OpenLdap database. + +"admins-ldap-server" block contains admin group and admin users. The "ldap-server" block has all the rest of the users. See below for the full list of users. + +This blocks are here to help with testing multiple LDAP servers, for any other LDAP related development and testing "openldap" block should be used. + +## Enabling LDAP in Grafana + +Copy the ldap_dev.toml file in this folder into your `conf` folder (it is gitignored already). To enable it in the .ini file to get Grafana to use this block: + +```ini +[auth.ldap] +enabled = true +config_file = conf/ldap_dev.toml +; allow_sign_up = true +``` + +## Groups & Users + +admins + ldap-admin + ldap-torkel +backend + ldap-carl + ldap-torkel + ldap-leo +frontend + ldap-torkel + ldap-tobias + ldap-daniel +editors + ldap-editor +no groups + ldap-viewer diff --git a/devenv/docker/blocks/multiple-openldap/prepopulate.sh b/devenv/docker/blocks/multiple-openldap/prepopulate.sh new file mode 100755 index 000000000000..aa11f8aba4f7 --- /dev/null +++ b/devenv/docker/blocks/multiple-openldap/prepopulate.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +echo "Pre-populating ldap entries, first waiting for ldap to start" + +sleep 3 + +adminUserDn="cn=admin,dc=grafana,dc=org" +adminPassword="grafana" + +for file in `ls /etc/ldap/prepopulate/*.ldif`; do + ldapadd -x -D $adminUserDn -w $adminPassword -f "$file" +done + + diff --git a/devenv/docker/blocks/openldap/Dockerfile b/devenv/docker/blocks/openldap/Dockerfile index 76172e133a45..b0d23b9e0c91 100644 --- a/devenv/docker/blocks/openldap/Dockerfile +++ b/devenv/docker/blocks/openldap/Dockerfile @@ -2,7 +2,7 @@ FROM debian:jessie -LABEL maintainer="Christian Luginbühl " +LABEL maintainer="Grafana team " ENV OPENLDAP_VERSION 2.4.40 diff --git a/devenv/docker/blocks/openldap/notes.md b/devenv/docker/blocks/openldap/notes.md index fb4130859706..a74c1427901f 100644 --- a/devenv/docker/blocks/openldap/notes.md +++ b/devenv/docker/blocks/openldap/notes.md @@ -2,8 +2,6 @@ Any ldif files added to the prepopulate subdirectory will be automatically imported into the OpenLdap database. -The ldif files add eight users, `ldap-admin`, `ldap-editor`, `ldap-viewer`, `ldap-carl`, `ldap-daniel`, `ldap-leo`, `ldap-tobias` and `ldap-torkel`. Two groups, `admins` and `users`, are added that correspond with the group mappings in the default conf/ldap.toml. `ldap-admin` is a member of `admins` and `ldap-editor` is a member of `users`. - Note that users that are added here need to specify a `memberOf` attribute manually as well as the `member` attribute for the group. The `memberOf` module usually does this automatically (if you add a group in Apache Directory Studio for example) but this does not work in the entrypoint script as it uses the `slapadd` command to add entries before the server has started and before the `memberOf` module is loaded. After adding ldif files to `prepopulate`: @@ -23,12 +21,11 @@ config_file = conf/ldap_dev.toml ; allow_sign_up = true ``` -Test groups & users +## Groups & Users admins ldap-admin ldap-torkel - ldap-daniel backend ldap-carl ldap-torkel From 597c380ead0c5a3d75845e4210eab3cfe337432b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Mon, 13 May 2019 13:18:14 +0200 Subject: [PATCH 011/166] Gauge: tweaks to background color and height usage (#17019) --- packages/grafana-ui/src/components/Gauge/Gauge.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/grafana-ui/src/components/Gauge/Gauge.tsx b/packages/grafana-ui/src/components/Gauge/Gauge.tsx index b45712ac9b0b..026b9769a708 100644 --- a/packages/grafana-ui/src/components/Gauge/Gauge.tsx +++ b/packages/grafana-ui/src/components/Gauge/Gauge.tsx @@ -69,14 +69,14 @@ export class Gauge extends PureComponent { const backgroundColor = selectThemeVariant( { - dark: theme.colors.dark3, - light: '#e6e6e6', + dark: theme.colors.dark8, + light: theme.colors.gray6, }, theme.type ); const gaugeWidthReduceRatio = showThresholdLabels ? 1.5 : 1; - const gaugeWidth = Math.min(dimension / 6, 40) / gaugeWidthReduceRatio; + const gaugeWidth = Math.min(dimension / 5, 40) / gaugeWidthReduceRatio; const thresholdMarkersWidth = gaugeWidth / 5; const fontSize = Math.min(dimension / 5.5, 100) * (value.text !== null ? this.getFontScale(value.text.length) : 1); const thresholdLabelFontSize = fontSize / 2.5; @@ -181,7 +181,7 @@ function calculateGaugeAutoProps(width: number, height: number, title: string | const titleFontSize = Math.min((width * 0.15) / 1.5, 20); // 20% of height * line-height, max 40px const titleHeight = titleFontSize * 1.5; const availableHeight = showLabel ? height - titleHeight : height; - const gaugeHeight = Math.min(availableHeight * 0.7, width); + const gaugeHeight = Math.min(availableHeight, width); return { showLabel, From 29ad72f0484bcac0225cbeaa89dcd7c298812d72 Mon Sep 17 00:00:00 2001 From: Oleg Gaidarenko Date: Mon, 13 May 2019 14:56:36 +0300 Subject: [PATCH 012/166] Chore: reintroduce gosec (#17021) It seems gosec memory issue was recently fixed. We should be good to go again Ref securego/gosec#307 --- pkg/services/notifications/codes.go | 2 +- scripts/backend-lint.sh | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/pkg/services/notifications/codes.go b/pkg/services/notifications/codes.go index 6382b609036b..b2bc9439549f 100644 --- a/pkg/services/notifications/codes.go +++ b/pkg/services/notifications/codes.go @@ -1,7 +1,7 @@ package notifications import ( - "crypto/sha1" + "crypto/sha1" // #nosec "encoding/hex" "fmt" "time" diff --git a/scripts/backend-lint.sh b/scripts/backend-lint.sh index 064b8626fb2c..5c337d2d2ea3 100755 --- a/scripts/backend-lint.sh +++ b/scripts/backend-lint.sh @@ -15,7 +15,7 @@ go get -u github.com/alecthomas/gometalinter go get -u github.com/jgautheron/goconst/cmd/goconst go get -u honnef.co/go/tools/cmd/staticcheck go get -u github.com/mgechev/revive -#go get -u github.com/securego/gosec/cmd/gosec/... +go get -u github.com/securego/gosec/cmd/gosec/... go get -u github.com/golangci/golangci-lint/cmd/golangci-lint # use gometalinter when lints are not available in golangci or @@ -39,7 +39,7 @@ exit_if_fail go vet ./pkg/... exit_if_fail revive -formatter stylish -config ./scripts/revive.toml # TODO recheck the rules and leave only necessary exclusions -# exit_if_fail gosec -quiet \ -# -exclude=G104,G107,G201,G202,G204,G301,G304,G401,G402,G501 \ -# -conf=./scripts/gosec.json \ -# ./pkg/... +exit_if_fail gosec -quiet \ + -exclude=G104,G107,G201,G202,G204,G301,G304,G401,G402,G501 \ + -conf=./scripts/gosec.json \ + ./pkg/... From 719c1c277fc403437e49d72307364d5ab77bec38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Mon, 13 May 2019 14:00:29 +0200 Subject: [PATCH 013/166] Devenv: Updated gauge test dashboard --- .../panel-gauge/gauge-multi-series.json | 271 ++++++++---------- 1 file changed, 120 insertions(+), 151 deletions(-) diff --git a/devenv/dev-dashboards/panel-gauge/gauge-multi-series.json b/devenv/dev-dashboards/panel-gauge/gauge-multi-series.json index 2f89d3ea9f31..3e1428a98657 100644 --- a/devenv/dev-dashboards/panel-gauge/gauge-multi-series.json +++ b/devenv/dev-dashboards/panel-gauge/gauge-multi-series.json @@ -21,79 +21,62 @@ "datasource": "gdev-testdata", "gridPos": { "h": 8, - "w": 24, + "w": 20, "x": 0, "y": 0 }, "id": 6, "links": [], - "options-gauge": { - "decimals": 0, - "maxValue": 100, - "minValue": 0, - "options": { - "decimals": 0, - "maxValue": 100, - "minValue": 0, - "prefix": "", - "showThresholdLabels": false, - "showThresholdMarkers": true, - "stat": "avg", - "suffix": "", - "thresholds": [], - "unit": "none", - "valueMappings": [] + "options": { + "fieldOptions": { + "calcs": ["mean"], + "defaults": { + "decimals": 0, + "max": 100, + "min": 0, + "unit": "none" + }, + "mappings": [], + "override": {}, + "thresholds": [ + { + "color": "#7EB26D", + "index": 0, + "value": null + }, + { + "color": "#EAB839", + "index": 1, + "value": 50 + }, + { + "color": "#6ED0E0", + "index": 2, + "value": 75 + }, + { + "color": "#EF843C", + "index": 3, + "value": 87.5 + }, + { + "color": "#E24D42", + "index": 4, + "value": 93.75 + }, + { + "color": "#1F78C1", + "index": 5, + "value": 96.875 + } + ], + "values": false }, - "prefix": "", + "orientation": "auto", "showThresholdLabels": false, - "showThresholdMarkers": true, - "stat": "avg", - "suffix": "", - "thresholds": [ - { - "color": "#1F78C1", - "index": 5, - "value": 96.875 - }, - { - "color": "#E24D42", - "index": 4, - "value": 93.75 - }, - { - "color": "#EF843C", - "index": 3, - "value": 87.5 - }, - { - "color": "#6ED0E0", - "index": 2, - "value": 75 - }, - { - "color": "#EAB839", - "index": 1, - "value": 50 - }, - { - "color": "#7EB26D", - "index": 0, - "value": null - } - ], - "unit": "none", - "valueMappings": [ - { - "from": "50", - "id": 1, - "operator": "", - "text": "Hello :) ", - "to": "90", - "type": 2, - "value": "" - } - ] + "showThresholdMarkers": true }, + "pluginVersion": "6.3.0-pre", "targets": [ { "refId": "A", @@ -124,50 +107,48 @@ { "datasource": "gdev-testdata", "gridPos": { - "h": 8, - "w": 24, - "x": 0, - "y": 8 + "h": 28, + "w": 4, + "x": 20, + "y": 0 }, - "id": 2, + "id": 4, "links": [], - "options-gauge": { - "decimals": 0, - "maxValue": 100, - "minValue": 0, - "options": { - "decimals": 0, - "maxValue": 100, - "minValue": 0, - "prefix": "", - "showThresholdLabels": false, - "showThresholdMarkers": true, - "stat": "avg", - "suffix": "", - "thresholds": [], - "unit": "none", - "valueMappings": [] + "options": { + "fieldOptions": { + "calcs": ["max"], + "defaults": { + "decimals": 0, + "max": "200", + "min": 0, + "unit": "none" + }, + "mappings": [], + "override": {}, + "thresholds": [ + { + "color": "#7EB26D", + "index": 0, + "value": null + }, + { + "color": "#EAB839", + "index": 1, + "value": 50 + }, + { + "color": "#6ED0E0", + "index": 2, + "value": 75 + } + ], + "values": false }, - "prefix": "", + "orientation": "auto", "showThresholdLabels": false, - "showThresholdMarkers": true, - "stat": "avg", - "suffix": "", - "thresholds": [ - { - "color": "#EAB839", - "index": 1, - "value": 50 - }, - { - "color": "#7EB26D", - "index": 0, - "value": null - } - ], - "unit": "none", - "valueMappings": [] + "showThresholdMarkers": true }, + "pluginVersion": "6.3.0-pre", "targets": [ { "refId": "A", @@ -192,61 +173,49 @@ ], "timeFrom": null, "timeShift": null, - "title": "Repeat horizontal", + "title": "Vertical", "type": "gauge" }, { "datasource": "gdev-testdata", "gridPos": { - "h": 14, - "w": 5, + "h": 20, + "w": 20, "x": 0, - "y": 16 + "y": 8 }, - "id": 4, + "id": 2, "links": [], - "options-gauge": { - "decimals": 0, - "maxValue": "200", - "minValue": 0, - "options": { - "decimals": 0, - "maxValue": 100, - "minValue": 0, - "prefix": "", - "showThresholdLabels": false, - "showThresholdMarkers": true, - "stat": "avg", - "suffix": "", - "thresholds": [], - "unit": "none", - "valueMappings": [] + "options": { + "fieldOptions": { + "calcs": ["mean"], + "defaults": { + "decimals": 0, + "max": 100, + "min": 0, + "unit": "none" + }, + "mappings": [], + "override": {}, + "thresholds": [ + { + "color": "#7EB26D", + "index": 0, + "value": null + }, + { + "color": "#EAB839", + "index": 1, + "value": 50 + } + ], + "values": false }, - "prefix": "", + "orientation": "auto", "showThresholdLabels": false, - "showThresholdMarkers": true, - "stat": "max", - "suffix": "", - "thresholds": [ - { - "color": "#6ED0E0", - "index": 2, - "value": 75 - }, - { - "color": "#EAB839", - "index": 1, - "value": 50 - }, - { - "color": "#7EB26D", - "index": 0, - "value": null - } - ], - "unit": "none", - "valueMappings": [] + "showThresholdMarkers": true }, + "pluginVersion": "6.3.0-pre", "targets": [ { "refId": "A", @@ -271,11 +240,11 @@ ], "timeFrom": null, "timeShift": null, - "title": "Vertical", + "title": "Repeat horizontal", "type": "gauge" } ], - "schemaVersion": 17, + "schemaVersion": 18, "style": "dark", "tags": ["panel-tests", "gdev", "gauge"], "templating": { @@ -292,5 +261,5 @@ "timezone": "", "title": "Panel Tests - Gauge Multi Series", "uid": "szkuR1umk", - "version": 7 + "version": 2 } From 3ce2f3b58db29340e3ec29fecab15bed0ba6f6a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torkel=20=C3=96degaard?= Date: Mon, 13 May 2019 15:49:54 +0200 Subject: [PATCH 014/166] Dashboard: show refresh button in kiosk mode (#17032) Fixes #16945 --- public/sass/components/_view_states.scss | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/public/sass/components/_view_states.scss b/public/sass/components/_view_states.scss index e1ca3d44f835..fbc50cfca3c8 100644 --- a/public/sass/components/_view_states.scss +++ b/public/sass/components/_view_states.scss @@ -16,8 +16,7 @@ } } - .navbar-button--zoom, - .navbar-button--refresh { + .navbar-button--zoom { display: none; } } From 01a7c1f0985daf7cc2b86ee27c5059e07439c54f Mon Sep 17 00:00:00 2001 From: Marcus Efraimsson Date: Mon, 13 May 2019 16:33:27 +0200 Subject: [PATCH 015/166] chore: remove x character in explore --- public/app/features/explore/Wrapper.tsx | 1 - 1 file changed, 1 deletion(-) diff --git a/public/app/features/explore/Wrapper.tsx b/public/app/features/explore/Wrapper.tsx index b73917e09ca3..e8b894bc53d8 100644 --- a/public/app/features/explore/Wrapper.tsx +++ b/public/app/features/explore/Wrapper.tsx @@ -36,7 +36,6 @@ export class Wrapper extends Component { )} - x ); From bbb1427f46a811911bd9553214adf61bc118687e Mon Sep 17 00:00:00 2001 From: Ryan McKinley Date: Mon, 13 May 2019 22:26:55 -0700 Subject: [PATCH 016/166] SeriesData: remove color from Field (#17044) --- packages/grafana-ui/src/types/data.ts | 1 - packages/grafana-ui/src/utils/displayValue.test.ts | 2 +- packages/grafana-ui/src/utils/displayValue.ts | 4 ++-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/packages/grafana-ui/src/types/data.ts b/packages/grafana-ui/src/types/data.ts index e629e76043a7..d1a1a7857776 100644 --- a/packages/grafana-ui/src/types/data.ts +++ b/packages/grafana-ui/src/types/data.ts @@ -47,7 +47,6 @@ export interface Field { unit?: string; dateFormat?: string; // Source data format decimals?: number | null; // Significant digits (for display) - color?: string; min?: number | null; max?: number | null; } diff --git a/packages/grafana-ui/src/utils/displayValue.test.ts b/packages/grafana-ui/src/utils/displayValue.test.ts index 63c78e979826..139286acc017 100644 --- a/packages/grafana-ui/src/utils/displayValue.test.ts +++ b/packages/grafana-ui/src/utils/displayValue.test.ts @@ -18,7 +18,7 @@ describe('Process simple display values', () => { getDisplayProcessor(), // Add a simple option that is not used (uses a different base class) - getDisplayProcessor({ field: { color: '#FFF' } }), + getDisplayProcessor({ field: { min: 0, max: 100 } }), // Add a simple option that is not used (uses a different base class) getDisplayProcessor({ field: { unit: 'locale' } }), diff --git a/packages/grafana-ui/src/utils/displayValue.ts b/packages/grafana-ui/src/utils/displayValue.ts index 59a04fefc2b9..6565985f4451 100644 --- a/packages/grafana-ui/src/utils/displayValue.ts +++ b/packages/grafana-ui/src/utils/displayValue.ts @@ -42,7 +42,7 @@ export function getDisplayProcessor(options?: DisplayValueOptions): DisplayProce return (value: any) => { const { mappings, thresholds, theme } = options; - let color = field.color; + let color; let text = _.toString(value); let numeric = toNumber(value); @@ -76,7 +76,7 @@ export function getDisplayProcessor(options?: DisplayValueOptions): DisplayProce const { decimals, scaledDecimals } = getDecimalsForValue(value, field.decimals); text = formatFunc(numeric, decimals, scaledDecimals, options.isUtc); } - if (thresholds && thresholds.length > 0) { + if (thresholds && thresholds.length) { color = getColorFromThreshold(numeric, thresholds, theme); } } From 1001cd7ac37a71f7935b6bfaa7a399a8ae7e4ff2 Mon Sep 17 00:00:00 2001 From: Johannes Schill Date: Tue, 14 May 2019 07:36:19 +0200 Subject: [PATCH 017/166] Dashboard: Fixes scrolling issues for Edge browser (#17033) * Fix: Only set scrollTop on CustomScroll element when it's needed and move arrow functions out of the props * Fix: Update snapshots * Minor refactoring to reuse same functions when rendering custom scrollbar Fixes #16796 --- .../CustomScrollbar/CustomScrollbar.tsx | 75 ++++++++++++------- .../CustomScrollbar.test.tsx.snap | 4 +- .../__snapshots__/ServerStats.test.tsx.snap | 4 +- .../dashboard/containers/DashboardPage.tsx | 12 +-- .../__snapshots__/DashboardPage.test.tsx.snap | 4 +- 5 files changed, 59 insertions(+), 40 deletions(-) diff --git a/packages/grafana-ui/src/components/CustomScrollbar/CustomScrollbar.tsx b/packages/grafana-ui/src/components/CustomScrollbar/CustomScrollbar.tsx index f2f6b236e14b..3546148f57c7 100644 --- a/packages/grafana-ui/src/components/CustomScrollbar/CustomScrollbar.tsx +++ b/packages/grafana-ui/src/components/CustomScrollbar/CustomScrollbar.tsx @@ -42,9 +42,10 @@ export class CustomScrollbar extends Component { updateScroll() { const ref = this.ref.current; + const { scrollTop } = this.props; - if (ref && !isNil(this.props.scrollTop)) { - ref.scrollTop(this.props.scrollTop); + if (ref && !isNil(scrollTop)) { + ref.scrollTop(scrollTop); } } @@ -70,6 +71,44 @@ export class CustomScrollbar extends Component { this.updateScroll(); } + renderTrack = (track: 'track-vertical' | 'track-horizontal', hideTrack: boolean | undefined, passedProps: any) => { + return ( +
    + ); + }; + + renderThumb = (thumb: 'thumb-horizontal' | 'thumb-vertical', passedProps: any) => { + return
    ; + }; + + renderTrackHorizontal = (passedProps: any) => { + return this.renderTrack('track-horizontal', this.props.hideHorizontalTrack, passedProps); + }; + + renderTrackVertical = (passedProps: any) => { + return this.renderTrack('track-vertical', this.props.hideVerticalTrack, passedProps); + }; + + renderThumbHorizontal = (passedProps: any) => { + return this.renderThumb('thumb-horizontal', passedProps); + }; + + renderThumbVertical = (passedProps: any) => { + return this.renderThumb('thumb-vertical', passedProps); + }; + + renderView = (passedProps: any) => { + return
    ; + }; + render() { const { className, @@ -80,8 +119,6 @@ export class CustomScrollbar extends Component { autoHide, autoHideTimeout, hideTracksWhenNotNeeded, - hideHorizontalTrack, - hideVerticalTrack, } = this.props; return ( @@ -97,31 +134,11 @@ export class CustomScrollbar extends Component { // Before these where set to inhert but that caused problems with cut of legends in firefox autoHeightMax={autoHeightMax} autoHeightMin={autoHeightMin} - renderTrackHorizontal={props => ( -
    - )} - renderTrackVertical={props => ( -
    - )} - renderThumbHorizontal={props =>
    } - renderThumbVertical={props =>
    } - renderView={props =>
    } + renderTrackHorizontal={this.renderTrackHorizontal} + renderTrackVertical={this.renderTrackVertical} + renderThumbHorizontal={this.renderThumbHorizontal} + renderThumbVertical={this.renderThumbVertical} + renderView={this.renderView} > {children} diff --git a/packages/grafana-ui/src/components/CustomScrollbar/__snapshots__/CustomScrollbar.test.tsx.snap b/packages/grafana-ui/src/components/CustomScrollbar/__snapshots__/CustomScrollbar.test.tsx.snap index b348f7dd8bd0..2d941bb1767b 100644 --- a/packages/grafana-ui/src/components/CustomScrollbar/__snapshots__/CustomScrollbar.test.tsx.snap +++ b/packages/grafana-ui/src/components/CustomScrollbar/__snapshots__/CustomScrollbar.test.tsx.snap @@ -37,7 +37,7 @@ exports[`CustomScrollbar renders correctly 1`] = `

    { showLoadingState: false, fullscreenPanel: null, scrollTop: 0, + updateScrollTop: null, rememberScrollTop: 0, }; @@ -168,7 +170,7 @@ export class DashboardPage extends PureComponent { isEditing: false, isFullscreen: false, fullscreenPanel: null, - scrollTop: this.state.rememberScrollTop, + updateScrollTop: this.state.rememberScrollTop, }, this.triggerPanelsRendering.bind(this) ); @@ -204,7 +206,7 @@ export class DashboardPage extends PureComponent { setScrollTop = (e: MouseEvent): void => { const target = e.target as HTMLElement; - this.setState({ scrollTop: target.scrollTop }); + this.setState({ scrollTop: target.scrollTop, updateScrollTop: null }); }; onAddPanel = () => { @@ -251,7 +253,7 @@ export class DashboardPage extends PureComponent { render() { const { dashboard, editview, $injector, isInitSlow, initError } = this.props; - const { isSettingsOpening, isEditing, isFullscreen, scrollTop } = this.state; + const { isSettingsOpening, isEditing, isFullscreen, scrollTop, updateScrollTop } = this.state; if (!dashboard) { if (isInitSlow) { @@ -285,9 +287,9 @@ export class DashboardPage extends PureComponent { />
    diff --git a/public/app/features/dashboard/containers/__snapshots__/DashboardPage.test.tsx.snap b/public/app/features/dashboard/containers/__snapshots__/DashboardPage.test.tsx.snap index 20fc00cafc01..d6be7658841b 100644 --- a/public/app/features/dashboard/containers/__snapshots__/DashboardPage.test.tsx.snap +++ b/public/app/features/dashboard/containers/__snapshots__/DashboardPage.test.tsx.snap @@ -111,7 +111,7 @@ exports[`DashboardPage Dashboard init completed Should render dashboard grid 1` autoHideTimeout={200} className="custom-scrollbar--page" hideTracksWhenNotNeeded={false} - scrollTop={0} + scrollTop={null} setScrollTop={[Function]} updateAfterMountMs={500} > @@ -349,7 +349,7 @@ exports[`DashboardPage When dashboard has editview url state should render setti autoHideTimeout={200} className="custom-scrollbar--page" hideTracksWhenNotNeeded={false} - scrollTop={0} + scrollTop={null} setScrollTop={[Function]} updateAfterMountMs={500} > From a87a763d83fb72a825fee1e5c575dd95d82be394 Mon Sep 17 00:00:00 2001 From: Ryan McKinley Date: Mon, 13 May 2019 22:55:49 -0700 Subject: [PATCH 018/166] DataSourcePlugin: support custom tabs (#16859) * use ConfigEditor * add tabs * add tabs * set the nav in state * remove actions * reorder imports * catch plugin loading errors * better text * keep props * fix typo * update snapshot * rename tab to page * add missing pages --- packages/grafana-ui/src/types/plugin.ts | 18 +- .../settings/DataSourceSettingsPage.test.tsx | 3 +- .../settings/DataSourceSettingsPage.tsx | 211 ++++++++++++------ .../datasources/settings/PluginSettings.tsx | 2 +- .../DataSourceSettingsPage.test.tsx.snap | 143 ------------ .../app/features/datasources/state/actions.ts | 5 +- .../features/datasources/state/navModel.ts | 61 +++-- public/app/features/plugins/PluginPage.tsx | 92 ++++---- .../{ExampleTab1.tsx => ExamplePage1.tsx} | 6 +- .../{ExampleTab2.tsx => ExamplePage2.tsx} | 6 +- public/app/plugins/app/example-app/module.ts | 20 +- .../datasource/testdata/TestInfoTab.tsx | 28 +++ .../plugins/datasource/testdata/module.tsx | 9 +- public/app/routes/routes.ts | 1 + 14 files changed, 300 insertions(+), 305 deletions(-) rename public/app/plugins/app/example-app/config/{ExampleTab1.tsx => ExamplePage1.tsx} (65%) rename public/app/plugins/app/example-app/config/{ExampleTab2.tsx => ExamplePage2.tsx} (65%) create mode 100644 public/app/plugins/datasource/testdata/TestInfoTab.tsx diff --git a/packages/grafana-ui/src/types/plugin.ts b/packages/grafana-ui/src/types/plugin.ts index c083fd95be38..72e9d2453fd5 100644 --- a/packages/grafana-ui/src/types/plugin.ts +++ b/packages/grafana-ui/src/types/plugin.ts @@ -91,17 +91,17 @@ export interface PluginMetaInfo { version: string; } -export interface PluginConfigTabProps { - meta: T; +export interface PluginConfigPageProps { + plugin: T; query: { [s: string]: any }; // The URL query parameters } -export interface PluginConfigTab { +export interface PluginConfigPage { title: string; // Display icon?: string; id: string; // Unique, in URL - body: ComponentClass>; + body: ComponentClass>; } export class GrafanaPlugin { @@ -112,14 +112,14 @@ export class GrafanaPlugin { angularConfigCtrl?: any; // Show configuration tabs on the plugin page - configTabs?: Array>; + configPages?: Array>; // Tabs on the plugin page - addConfigTab(tab: PluginConfigTab) { - if (!this.configTabs) { - this.configTabs = []; + addConfigPage(tab: PluginConfigPage) { + if (!this.configPages) { + this.configPages = []; } - this.configTabs.push(tab); + this.configPages.push(tab); return this; } } diff --git a/public/app/features/datasources/settings/DataSourceSettingsPage.test.tsx b/public/app/features/datasources/settings/DataSourceSettingsPage.test.tsx index 575311c2d174..6f9939e882b9 100644 --- a/public/app/features/datasources/settings/DataSourceSettingsPage.test.tsx +++ b/public/app/features/datasources/settings/DataSourceSettingsPage.test.tsx @@ -19,7 +19,7 @@ const setup = (propOverrides?: object) => { setDataSourceName, updateDataSource: jest.fn(), setIsDefault, - plugin: pluginMock, + query: {}, ...propOverrides, }; @@ -45,7 +45,6 @@ describe('Render', () => { it('should render beta info text', () => { const wrapper = setup({ dataSourceMeta: { ...getMockPlugin(), state: 'beta' }, - plugin: pluginMock, }); expect(wrapper).toMatchSnapshot(); diff --git a/public/app/features/datasources/settings/DataSourceSettingsPage.tsx b/public/app/features/datasources/settings/DataSourceSettingsPage.tsx index e02684d57fcc..5c31b946149c 100644 --- a/public/app/features/datasources/settings/DataSourceSettingsPage.tsx +++ b/public/app/features/datasources/settings/DataSourceSettingsPage.tsx @@ -2,6 +2,7 @@ import React, { PureComponent } from 'react'; import { hot } from 'react-hot-loader'; import { connect } from 'react-redux'; +import isString from 'lodash/isString'; // Components import Page from 'app/core/components/Page/Page'; @@ -21,7 +22,7 @@ import { getNavModel } from 'app/core/selectors/navModel'; import { getRouteParamsId } from 'app/core/selectors/location'; // Types -import { StoreState } from 'app/types/'; +import { StoreState, UrlQueryMap } from 'app/types/'; import { NavModel, DataSourceSettings, DataSourcePluginMeta } from '@grafana/ui'; import { getDataSourceLoadingNav } from '../state/navModel'; import PluginStateinfo from 'app/features/plugins/PluginStateInfo'; @@ -38,14 +39,17 @@ export interface Props { updateDataSource: typeof updateDataSource; setIsDefault: typeof setIsDefault; plugin?: GenericDataSourcePlugin; + query: UrlQueryMap; + page?: string; } interface State { dataSource: DataSourceSettings; - plugin: GenericDataSourcePlugin; + plugin?: GenericDataSourcePlugin; isTesting?: boolean; testingMessage?: string; testingStatus?: string; + loadError?: any; } export class DataSourceSettingsPage extends PureComponent { @@ -73,9 +77,17 @@ export class DataSourceSettingsPage extends PureComponent { async componentDidMount() { const { loadDataSource, pageId } = this.props; - await loadDataSource(pageId); - if (!this.state.plugin) { - await this.loadPlugin(); + if (isNaN(pageId)) { + this.setState({ loadError: 'Invalid ID' }); + return; + } + try { + await loadDataSource(pageId); + if (!this.state.plugin) { + await this.loadPlugin(); + } + } catch (err) { + this.setState({ loadError: err }); } } @@ -174,70 +186,133 @@ export class DataSourceSettingsPage extends PureComponent { return this.state.dataSource.id > 0; } - render() { - const { dataSourceMeta, navModel, setDataSourceName, setIsDefault } = this.props; - const { testingMessage, testingStatus, plugin, dataSource } = this.state; + renderLoadError(loadError: any) { + let showDelete = false; + let msg = loadError.toString(); + if (loadError.data) { + if (loadError.data.message) { + msg = loadError.data.message; + } + } else if (isString(loadError)) { + showDelete = true; + } + + const node = { + text: msg, + subTitle: 'Data Source Error', + icon: 'fa fa-fw fa-warning', + }; + const nav = { + node: node, + main: node, + }; return ( - - - {this.hasDataSource && ( -
    -
    - {this.isReadOnly() && this.renderIsReadOnlyMessage()} - {dataSourceMeta.state && ( -
    - - -
    - )} + + +
    +
    + {showDelete && ( + + )} + + Back + +
    +
    +
    +
    + ); + } - setIsDefault(state)} - onNameChange={name => setDataSourceName(name)} - /> - - {dataSourceMeta.module && plugin && ( - - )} + renderConfigPageBody(page: string) { + const { plugin } = this.state; + if (!plugin || !plugin.configPages) { + return null; // still loading + } + + for (const p of plugin.configPages) { + if (p.id === page) { + return ; + } + } + + return
    Page Not Found: {page}
    ; + } + + renderSettings() { + const { dataSourceMeta, setDataSourceName, setIsDefault } = this.props; + const { testingMessage, testingStatus, dataSource, plugin } = this.state; -
    - {testingMessage && ( -
    -
    - {testingStatus === 'error' ? ( - - ) : ( - - )} -
    -
    -
    - {testingMessage} -
    -
    -
    - )} -
    - - this.onSubmit(event)} - isReadOnly={this.isReadOnly()} - onDelete={this.onDelete} - onTest={event => this.onTest(event)} - /> - + return ( +
    + {this.isReadOnly() && this.renderIsReadOnlyMessage()} + {dataSourceMeta.state && ( +
    + + +
    + )} + + setIsDefault(state)} + onNameChange={name => setDataSourceName(name)} + /> + + {plugin && ( + + )} + +
    + {testingMessage && ( +
    +
    + {testingStatus === 'error' ? ( + + ) : ( + + )} +
    +
    +
    {testingMessage}
    +
    )} +
    + + this.onSubmit(event)} + isReadOnly={this.isReadOnly()} + onDelete={this.onDelete} + onTest={event => this.onTest(event)} + /> + + ); + } + + render() { + const { navModel, page } = this.props; + const { loadError } = this.state; + + if (loadError) { + return this.renderLoadError(loadError); + } + + return ( + + + {this.hasDataSource &&
    {page ? this.renderConfigPageBody(page) : this.renderSettings()}
    }
    ); @@ -247,11 +322,19 @@ export class DataSourceSettingsPage extends PureComponent { function mapStateToProps(state: StoreState) { const pageId = getRouteParamsId(state.location); const dataSource = getDataSource(state.dataSources, pageId); + const page = state.location.query.page as string; + return { - navModel: getNavModel(state.navIndex, `datasource-settings-${pageId}`, getDataSourceLoadingNav('settings')), + navModel: getNavModel( + state.navIndex, + page ? `datasource-page-${page}` : `datasource-settings-${pageId}`, + getDataSourceLoadingNav('settings') + ), dataSource: getDataSource(state.dataSources, pageId), dataSourceMeta: getDataSourceMeta(state.dataSources, dataSource.type), pageId: pageId, + query: state.location.query, + page, }; } diff --git a/public/app/features/datasources/settings/PluginSettings.tsx b/public/app/features/datasources/settings/PluginSettings.tsx index 94c054d56ee9..a7462cbb45c7 100644 --- a/public/app/features/datasources/settings/PluginSettings.tsx +++ b/public/app/features/datasources/settings/PluginSettings.tsx @@ -54,7 +54,7 @@ export class PluginSettings extends PureComponent { } } - componentDidUpdate(prevProps) { + componentDidUpdate(prevProps: Props) { const { plugin } = this.props; if (!plugin.components.ConfigEditor && this.props.dataSource !== prevProps.dataSource) { this.scopeProps.ctrl.current = _.cloneDeep(this.props.dataSource); diff --git a/public/app/features/datasources/settings/__snapshots__/DataSourceSettingsPage.test.tsx.snap b/public/app/features/datasources/settings/__snapshots__/DataSourceSettingsPage.test.tsx.snap index 2ca6a2ee28f0..063ebf8418de 100644 --- a/public/app/features/datasources/settings/__snapshots__/DataSourceSettingsPage.test.tsx.snap +++ b/public/app/features/datasources/settings/__snapshots__/DataSourceSettingsPage.test.tsx.snap @@ -153,78 +153,6 @@ exports[`Render should render beta info text 1`] = ` onDefaultChange={[Function]} onNameChange={[Function]} /> -
    @@ -257,77 +185,6 @@ exports[`Render should render component 1`] = ` onDefaultChange={[Function]} onNameChange={[Function]} /> -
    diff --git a/public/app/features/datasources/state/actions.ts b/public/app/features/datasources/state/actions.ts index a74943aa9ecf..a09289500693 100644 --- a/public/app/features/datasources/state/actions.ts +++ b/public/app/features/datasources/state/actions.ts @@ -10,6 +10,7 @@ import { StoreState, LocationUpdate } from 'app/types'; import { actionCreatorFactory } from 'app/core/redux'; import { ActionOf, noPayloadActionCreatorFactory } from 'app/core/redux/actionCreatorFactory'; import { getPluginSettings } from 'app/features/plugins/PluginSettingsCache'; +import { importDataSourcePlugin } from 'app/features/plugins/plugin_loader'; export const dataSourceLoaded = actionCreatorFactory('LOAD_DATA_SOURCE').create(); @@ -52,9 +53,11 @@ export function loadDataSource(id: number): ThunkResult { return async dispatch => { const dataSource = await getBackendSrv().get(`/api/datasources/${id}`); const pluginInfo = (await getPluginSettings(dataSource.type)) as DataSourcePluginMeta; + const plugin = await importDataSourcePlugin(pluginInfo); + dispatch(dataSourceLoaded(dataSource)); dispatch(dataSourceMetaLoaded(pluginInfo)); - dispatch(updateNavIndex(buildNavModel(dataSource, pluginInfo))); + dispatch(updateNavIndex(buildNavModel(dataSource, plugin))); }; } diff --git a/public/app/features/datasources/state/navModel.ts b/public/app/features/datasources/state/navModel.ts index 6fdc6f5762f8..6b5f679451de 100644 --- a/public/app/features/datasources/state/navModel.ts +++ b/public/app/features/datasources/state/navModel.ts @@ -1,7 +1,10 @@ -import { PluginMeta, DataSourceSettings, PluginType, NavModel, NavModelItem, PluginInclude } from '@grafana/ui'; +import { DataSourceSettings, PluginType, NavModel, NavModelItem, PluginInclude } from '@grafana/ui'; import config from 'app/core/config'; +import { GenericDataSourcePlugin } from '../settings/PluginSettings'; + +export function buildNavModel(dataSource: DataSourceSettings, plugin: GenericDataSourcePlugin): NavModelItem { + const pluginMeta = plugin.meta; -export function buildNavModel(dataSource: DataSourceSettings, pluginMeta: PluginMeta): NavModelItem { const navModel = { img: pluginMeta.info.logos.large, id: 'datasource-' + dataSource.id, @@ -20,6 +23,18 @@ export function buildNavModel(dataSource: DataSourceSettings, pluginMeta: Plugin ], }; + if (plugin.configPages) { + for (const page of plugin.configPages) { + navModel.children.push({ + active: false, + text: page.title, + icon: page.icon, + url: `datasources/edit/${dataSource.id}/?page=${page.id}`, + id: `datasource-page-${page.id}`, + }); + } + } + if (pluginMeta.includes && hasDashboards(pluginMeta.includes)) { navModel.children.push({ active: false, @@ -65,28 +80,30 @@ export function getDataSourceLoadingNav(pageName: string): NavModel { user: '', }, { - id: '1', - type: PluginType.datasource, - name: '', - info: { - author: { - name: '', - url: '', - }, - description: '', - links: [{ name: '', url: '' }], - logos: { - large: '', - small: '', + meta: { + id: '1', + type: PluginType.datasource, + name: '', + info: { + author: { + name: '', + url: '', + }, + description: '', + links: [{ name: '', url: '' }], + logos: { + large: '', + small: '', + }, + screenshots: [], + updated: '', + version: '', }, - screenshots: [], - updated: '', - version: '', + includes: [], + module: '', + baseUrl: '', }, - includes: [], - module: '', - baseUrl: '', - } + } as GenericDataSourcePlugin ); let node: NavModelItem; diff --git a/public/app/features/plugins/PluginPage.tsx b/public/app/features/plugins/PluginPage.tsx index 176c03c6b6ca..9da5b097f2a7 100644 --- a/public/app/features/plugins/PluginPage.tsx +++ b/public/app/features/plugins/PluginPage.tsx @@ -74,12 +74,12 @@ interface State { loading: boolean; plugin?: GrafanaPlugin; nav: NavModel; - defaultTab: string; // The first configured one or readme + defaultPage: string; // The first configured one or readme } -const TAB_ID_README = 'readme'; -const TAB_ID_DASHBOARDS = 'dashboards'; -const TAB_ID_CONFIG_CTRL = 'config'; +const PAGE_ID_README = 'readme'; +const PAGE_ID_DASHBOARDS = 'dashboards'; +const PAGE_ID_CONFIG_CTRL = 'config'; class PluginPage extends PureComponent { constructor(props: Props) { @@ -87,7 +87,7 @@ class PluginPage extends PureComponent { this.state = { loading: true, nav: getLoadingNav(), - defaultTab: TAB_ID_README, + defaultPage: PAGE_ID_README, }; } @@ -103,14 +103,14 @@ class PluginPage extends PureComponent { } const { meta } = plugin; - let defaultTab: string; - const tabs: NavModelItem[] = []; + let defaultPage: string; + const pages: NavModelItem[] = []; if (true) { - tabs.push({ + pages.push({ text: 'Readme', icon: 'fa fa-fw fa-file-text-o', - url: path + '?tab=' + TAB_ID_README, - id: TAB_ID_README, + url: path + '?page=' + PAGE_ID_README, + id: PAGE_ID_README, }); } @@ -118,42 +118,42 @@ class PluginPage extends PureComponent { if (meta.type === PluginType.app) { // Legacy App Config if (plugin.angularConfigCtrl) { - tabs.push({ + pages.push({ text: 'Config', icon: 'gicon gicon-cog', - url: path + '?tab=' + TAB_ID_CONFIG_CTRL, - id: TAB_ID_CONFIG_CTRL, + url: path + '?page=' + PAGE_ID_CONFIG_CTRL, + id: PAGE_ID_CONFIG_CTRL, }); - defaultTab = TAB_ID_CONFIG_CTRL; + defaultPage = PAGE_ID_CONFIG_CTRL; } - if (plugin.configTabs) { - for (const tab of plugin.configTabs) { - tabs.push({ - text: tab.title, - icon: tab.icon, - url: path + '?tab=' + tab.id, - id: tab.id, + if (plugin.configPages) { + for (const page of plugin.configPages) { + pages.push({ + text: page.title, + icon: page.icon, + url: path + '?page=' + page.id, + id: page.id, }); - if (!defaultTab) { - defaultTab = tab.id; + if (!defaultPage) { + defaultPage = page.id; } } } - // Check for the dashboard tabs + // Check for the dashboard pages if (find(meta.includes, { type: 'dashboard' })) { - tabs.push({ + pages.push({ text: 'Dashboards', icon: 'gicon gicon-dashboard', - url: path + '?tab=' + TAB_ID_DASHBOARDS, - id: TAB_ID_DASHBOARDS, + url: path + '?page=' + PAGE_ID_DASHBOARDS, + id: PAGE_ID_DASHBOARDS, }); } } - if (!defaultTab) { - defaultTab = tabs[0].id; // the first tab + if (!defaultPage) { + defaultPage = pages[0].id; // the first tab } const node = { @@ -162,13 +162,13 @@ class PluginPage extends PureComponent { subTitle: meta.info.author.name, breadcrumbs: [{ title: 'Plugins', url: '/plugins' }], url: path, - children: this.setActiveTab(query.tab as string, tabs, defaultTab), + children: this.setActivePage(query.page as string, pages, defaultPage), }; this.setState({ loading: false, plugin, - defaultTab, + defaultPage, nav: { node: node, main: node, @@ -176,15 +176,15 @@ class PluginPage extends PureComponent { }); } - setActiveTab(tabId: string, tabs: NavModelItem[], defaultTabId: string): NavModelItem[] { + setActivePage(pageId: string, pages: NavModelItem[], defaultPageId: string): NavModelItem[] { let found = false; - const selected = tabId || defaultTabId; - const changed = tabs.map(tab => { - const active = !found && selected === tab.id; + const selected = pageId || defaultPageId; + const changed = pages.map(p => { + const active = !found && selected === p.id; if (active) { found = true; } - return { ...tab, active }; + return { ...p, active }; }); if (!found) { changed[0].active = true; @@ -193,13 +193,13 @@ class PluginPage extends PureComponent { } componentDidUpdate(prevProps: Props) { - const prevTab = prevProps.query.tab as string; - const tab = this.props.query.tab as string; - if (prevTab !== tab) { - const { nav, defaultTab } = this.state; + const prevPage = prevProps.query.page as string; + const page = this.props.query.page as string; + if (prevPage !== page) { + const { nav, defaultPage } = this.state; const node = { ...nav.node, - children: this.setActiveTab(tab, nav.node.children, defaultTab), + children: this.setActivePage(page, nav.node.children, defaultPage), }; this.setState({ nav: { @@ -221,21 +221,21 @@ class PluginPage extends PureComponent { const active = nav.main.children.find(tab => tab.active); if (active) { // Find the current config tab - if (plugin.configTabs) { - for (const tab of plugin.configTabs) { + if (plugin.configPages) { + for (const tab of plugin.configPages) { if (tab.id === active.id) { - return ; + return ; } } } // Apps have some special behavior if (plugin.meta.type === PluginType.app) { - if (active.id === TAB_ID_DASHBOARDS) { + if (active.id === PAGE_ID_DASHBOARDS) { return ; } - if (active.id === TAB_ID_CONFIG_CTRL && plugin.angularConfigCtrl) { + if (active.id === PAGE_ID_CONFIG_CTRL && plugin.angularConfigCtrl) { return ; } } diff --git a/public/app/plugins/app/example-app/config/ExampleTab1.tsx b/public/app/plugins/app/example-app/config/ExamplePage1.tsx similarity index 65% rename from public/app/plugins/app/example-app/config/ExampleTab1.tsx rename to public/app/plugins/app/example-app/config/ExamplePage1.tsx index cf79a880f435..c25eee35e535 100644 --- a/public/app/plugins/app/example-app/config/ExampleTab1.tsx +++ b/public/app/plugins/app/example-app/config/ExamplePage1.tsx @@ -2,11 +2,11 @@ import React, { PureComponent } from 'react'; // Types -import { PluginConfigTabProps, AppPluginMeta } from '@grafana/ui'; +import { PluginConfigPageProps, AppPlugin } from '@grafana/ui'; -interface Props extends PluginConfigTabProps {} +interface Props extends PluginConfigPageProps {} -export class ExampleTab1 extends PureComponent { +export class ExamplePage1 extends PureComponent { constructor(props: Props) { super(props); } diff --git a/public/app/plugins/app/example-app/config/ExampleTab2.tsx b/public/app/plugins/app/example-app/config/ExamplePage2.tsx similarity index 65% rename from public/app/plugins/app/example-app/config/ExampleTab2.tsx rename to public/app/plugins/app/example-app/config/ExamplePage2.tsx index bf2ae181405a..596bb88e9ba0 100644 --- a/public/app/plugins/app/example-app/config/ExampleTab2.tsx +++ b/public/app/plugins/app/example-app/config/ExamplePage2.tsx @@ -2,11 +2,11 @@ import React, { PureComponent } from 'react'; // Types -import { PluginConfigTabProps, AppPluginMeta } from '@grafana/ui'; +import { PluginConfigPageProps, AppPlugin } from '@grafana/ui'; -interface Props extends PluginConfigTabProps {} +interface Props extends PluginConfigPageProps {} -export class ExampleTab2 extends PureComponent { +export class ExamplePage2 extends PureComponent { constructor(props: Props) { super(props); } diff --git a/public/app/plugins/app/example-app/module.ts b/public/app/plugins/app/example-app/module.ts index 0b4a2ae646a9..f82f7faec08b 100644 --- a/public/app/plugins/app/example-app/module.ts +++ b/public/app/plugins/app/example-app/module.ts @@ -2,8 +2,8 @@ import { ExampleConfigCtrl } from './legacy/config'; import { AngularExamplePageCtrl } from './legacy/angular_example_page'; import { AppPlugin } from '@grafana/ui'; -import { ExampleTab1 } from './config/ExampleTab1'; -import { ExampleTab2 } from './config/ExampleTab2'; +import { ExamplePage1 } from './config/ExamplePage1'; +import { ExamplePage2 } from './config/ExamplePage2'; import { ExampleRootPage } from './ExampleRootPage'; // Legacy exports just for testing @@ -14,15 +14,15 @@ export { export const plugin = new AppPlugin() .setRootPage(ExampleRootPage) - .addConfigTab({ - title: 'Tab 1', + .addConfigPage({ + title: 'Page 1', icon: 'fa fa-info', - body: ExampleTab1, - id: 'tab1', + body: ExamplePage1, + id: 'page1', }) - .addConfigTab({ - title: 'Tab 2', + .addConfigPage({ + title: 'Page 2', icon: 'fa fa-user', - body: ExampleTab2, - id: 'tab2', + body: ExamplePage2, + id: 'page2', }); diff --git a/public/app/plugins/datasource/testdata/TestInfoTab.tsx b/public/app/plugins/datasource/testdata/TestInfoTab.tsx new file mode 100644 index 000000000000..686d8b94e4ab --- /dev/null +++ b/public/app/plugins/datasource/testdata/TestInfoTab.tsx @@ -0,0 +1,28 @@ +// Libraries +import React, { PureComponent } from 'react'; + +// Types +import { PluginConfigPageProps, DataSourcePlugin } from '@grafana/ui'; +import { TestDataDatasource } from './datasource'; + +interface Props extends PluginConfigPageProps> {} + +export class TestInfoTab extends PureComponent { + constructor(props: Props) { + super(props); + } + + render() { + return ( + + ); + } +} diff --git a/public/app/plugins/datasource/testdata/module.tsx b/public/app/plugins/datasource/testdata/module.tsx index 738149451b97..800f61db7370 100644 --- a/public/app/plugins/datasource/testdata/module.tsx +++ b/public/app/plugins/datasource/testdata/module.tsx @@ -1,6 +1,7 @@ import { DataSourcePlugin } from '@grafana/ui'; import { TestDataDatasource } from './datasource'; import { TestDataQueryCtrl } from './query_ctrl'; +import { TestInfoTab } from './TestInfoTab'; import { ConfigEditor } from './ConfigEditor'; class TestDataAnnotationsQueryCtrl { @@ -12,4 +13,10 @@ class TestDataAnnotationsQueryCtrl { export const plugin = new DataSourcePlugin(TestDataDatasource) .setConfigEditor(ConfigEditor) .setQueryCtrl(TestDataQueryCtrl) - .setAnnotationQueryCtrl(TestDataAnnotationsQueryCtrl); + .setAnnotationQueryCtrl(TestDataAnnotationsQueryCtrl) + .addConfigPage({ + title: 'Setup', + icon: 'fa fa-list-alt', + body: TestInfoTab, + id: 'setup', + }); diff --git a/public/app/routes/routes.ts b/public/app/routes/routes.ts index 9a7c9b5d2d50..a863797dea04 100644 --- a/public/app/routes/routes.ts +++ b/public/app/routes/routes.ts @@ -110,6 +110,7 @@ export function setupAngularRoutes($routeProvider, $locationProvider) { }) .when('/datasources/edit/:id/', { template: '', + reloadOnSearch: false, // for tabs resolve: { component: () => DataSourceSettingsPage, }, From 13f137a17d91eda5e15b6006f257dfa9c5171c19 Mon Sep 17 00:00:00 2001 From: Carl Bergquist Date: Tue, 14 May 2019 08:15:05 +0200 Subject: [PATCH 019/166] tech: avoid alias for importing models in alerting (#17041) ref #14679 --- pkg/services/alerting/commands.go | 8 ++-- pkg/services/alerting/conditions/query.go | 6 +-- .../alerting/conditions/query_test.go | 8 ++-- pkg/services/alerting/eval_context.go | 44 +++++++++---------- pkg/services/alerting/extractor.go | 36 +++++++-------- pkg/services/alerting/extractor_test.go | 36 +++++++-------- pkg/services/alerting/notifier.go | 19 ++++---- .../alerting/notifiers/alertmanager.go | 16 +++---- .../alerting/notifiers/alertmanager_test.go | 29 ++++++------ pkg/services/alerting/notifiers/dingding.go | 6 +-- .../alerting/notifiers/dingding_test.go | 6 +-- pkg/services/alerting/notifiers/discord.go | 8 ++-- .../alerting/notifiers/discord_test.go | 6 +-- pkg/services/alerting/notifiers/email.go | 9 ++-- pkg/services/alerting/notifiers/email_test.go | 8 ++-- pkg/services/alerting/notifiers/googlechat.go | 6 +-- .../alerting/notifiers/googlechat_test.go | 6 +-- .../alerting/notifiers/hipchat_test.go | 8 ++-- pkg/services/alerting/notifiers/kafka.go | 6 +-- pkg/services/alerting/notifiers/kafka_test.go | 6 +-- pkg/services/alerting/notifiers/line.go | 8 ++-- pkg/services/alerting/notifiers/line_test.go | 6 +-- pkg/services/alerting/notifiers/opsgenie.go | 12 ++--- .../alerting/notifiers/opsgenie_test.go | 6 +-- pkg/services/alerting/notifiers/pagerduty.go | 10 ++--- .../alerting/notifiers/pagerduty_test.go | 8 ++-- pkg/services/alerting/notifiers/pushover.go | 8 ++-- .../alerting/notifiers/pushover_test.go | 13 +++--- pkg/services/alerting/notifiers/sensu.go | 6 +-- pkg/services/alerting/notifiers/sensu_test.go | 6 +-- pkg/services/alerting/notifiers/slack.go | 10 ++--- pkg/services/alerting/notifiers/slack_test.go | 8 ++-- pkg/services/alerting/notifiers/teams.go | 8 ++-- pkg/services/alerting/notifiers/teams_test.go | 8 ++-- pkg/services/alerting/notifiers/telegram.go | 16 +++---- .../alerting/notifiers/telegram_test.go | 14 +++--- pkg/services/alerting/notifiers/threema.go | 12 ++--- .../alerting/notifiers/threema_test.go | 12 ++--- .../alerting/notifiers/victorops_test.go | 6 +-- pkg/services/alerting/notifiers/webhook.go | 6 +-- .../alerting/notifiers/webhook_test.go | 6 +-- pkg/services/alerting/reader.go | 5 +-- pkg/services/alerting/result_handler.go | 9 ++-- pkg/services/alerting/rule.go | 14 +++--- pkg/services/alerting/rule_test.go | 12 ++--- pkg/services/alerting/test_notification.go | 8 ++-- pkg/services/alerting/test_rule.go | 6 +-- 47 files changed, 261 insertions(+), 259 deletions(-) diff --git a/pkg/services/alerting/commands.go b/pkg/services/alerting/commands.go index dd2ff5658d60..887334ec7290 100644 --- a/pkg/services/alerting/commands.go +++ b/pkg/services/alerting/commands.go @@ -2,7 +2,7 @@ package alerting import ( "github.com/grafana/grafana/pkg/bus" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) func init() { @@ -10,14 +10,14 @@ func init() { bus.AddHandler("alerting", validateDashboardAlerts) } -func validateDashboardAlerts(cmd *m.ValidateDashboardAlertsCommand) error { +func validateDashboardAlerts(cmd *models.ValidateDashboardAlertsCommand) error { extractor := NewDashAlertExtractor(cmd.Dashboard, cmd.OrgId, cmd.User) return extractor.ValidateAlerts() } -func updateDashboardAlerts(cmd *m.UpdateDashboardAlertsCommand) error { - saveAlerts := m.SaveAlertsCommand{ +func updateDashboardAlerts(cmd *models.UpdateDashboardAlertsCommand) error { + saveAlerts := models.SaveAlertsCommand{ OrgId: cmd.OrgId, UserId: cmd.User.UserId, DashboardId: cmd.Dashboard.Id, diff --git a/pkg/services/alerting/conditions/query.go b/pkg/services/alerting/conditions/query.go index 7d1a276c42e6..37dbd9b3f7a6 100644 --- a/pkg/services/alerting/conditions/query.go +++ b/pkg/services/alerting/conditions/query.go @@ -10,7 +10,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/null" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/tsdb" ) @@ -100,7 +100,7 @@ func (c *QueryCondition) Eval(context *alerting.EvalContext) (*alerting.Conditio } func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange *tsdb.TimeRange) (tsdb.TimeSeriesSlice, error) { - getDsInfo := &m.GetDataSourceByIdQuery{ + getDsInfo := &models.GetDataSourceByIdQuery{ Id: c.Query.DatasourceId, OrgId: context.Rule.OrgId, } @@ -139,7 +139,7 @@ func (c *QueryCondition) executeQuery(context *alerting.EvalContext, timeRange * return result, nil } -func (c *QueryCondition) getRequestForAlertRule(datasource *m.DataSource, timeRange *tsdb.TimeRange) *tsdb.TsdbQuery { +func (c *QueryCondition) getRequestForAlertRule(datasource *models.DataSource, timeRange *tsdb.TimeRange) *tsdb.TsdbQuery { req := &tsdb.TsdbQuery{ TimeRange: timeRange, Queries: []*tsdb.Query{ diff --git a/pkg/services/alerting/conditions/query_test.go b/pkg/services/alerting/conditions/query_test.go index 0ea6470bc2d8..2e1ecf5f39c5 100644 --- a/pkg/services/alerting/conditions/query_test.go +++ b/pkg/services/alerting/conditions/query_test.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/null" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/tsdb" . "github.com/smartystreets/goconvey/convey" @@ -168,7 +168,7 @@ func (ctx *queryConditionTestContext) exec() (*alerting.ConditionResult, error) ctx.condition = condition - condition.HandleRequest = func(context context.Context, dsInfo *m.DataSource, req *tsdb.TsdbQuery) (*tsdb.Response, error) { + condition.HandleRequest = func(context context.Context, dsInfo *models.DataSource, req *tsdb.TsdbQuery) (*tsdb.Response, error) { return &tsdb.Response{ Results: map[string]*tsdb.QueryResult{ "A": {Series: ctx.series}, @@ -182,8 +182,8 @@ func (ctx *queryConditionTestContext) exec() (*alerting.ConditionResult, error) func queryConditionScenario(desc string, fn queryConditionScenarioFunc) { Convey(desc, func() { - bus.AddHandler("test", func(query *m.GetDataSourceByIdQuery) error { - query.Result = &m.DataSource{Id: 1, Type: "graphite"} + bus.AddHandler("test", func(query *models.GetDataSourceByIdQuery) error { + query.Result = &models.DataSource{Id: 1, Type: "graphite"} return nil }) diff --git a/pkg/services/alerting/eval_context.go b/pkg/services/alerting/eval_context.go index 6358c22a97f1..7d9a9014086b 100644 --- a/pkg/services/alerting/eval_context.go +++ b/pkg/services/alerting/eval_context.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" ) @@ -23,12 +23,12 @@ type EvalContext struct { Rule *Rule log log.Logger - dashboardRef *m.DashboardRef + dashboardRef *models.DashboardRef ImagePublicUrl string ImageOnDiskPath string NoDataFound bool - PrevAlertState m.AlertStateType + PrevAlertState models.AlertStateType Ctx context.Context } @@ -53,22 +53,22 @@ type StateDescription struct { func (c *EvalContext) GetStateModel() *StateDescription { switch c.Rule.State { - case m.AlertStateOK: + case models.AlertStateOK: return &StateDescription{ Color: "#36a64f", Text: "OK", } - case m.AlertStateNoData: + case models.AlertStateNoData: return &StateDescription{ Color: "#888888", Text: "No Data", } - case m.AlertStateAlerting: + case models.AlertStateAlerting: return &StateDescription{ Color: "#D63232", Text: "Alerting", } - case m.AlertStateUnknown: + case models.AlertStateUnknown: return &StateDescription{ Color: "#888888", Text: "Unknown", @@ -90,12 +90,12 @@ func (c *EvalContext) GetNotificationTitle() string { return "[" + c.GetStateModel().Text + "] " + c.Rule.Name } -func (c *EvalContext) GetDashboardUID() (*m.DashboardRef, error) { +func (c *EvalContext) GetDashboardUID() (*models.DashboardRef, error) { if c.dashboardRef != nil { return c.dashboardRef, nil } - uidQuery := &m.GetDashboardRefByIdQuery{Id: c.Rule.DashboardId} + uidQuery := &models.GetDashboardRefByIdQuery{Id: c.Rule.DashboardId} if err := bus.Dispatch(uidQuery); err != nil { return nil, err } @@ -115,29 +115,29 @@ func (c *EvalContext) GetRuleUrl() (string, error) { if err != nil { return "", err } - return fmt.Sprintf(urlFormat, m.GetFullDashboardUrl(ref.Uid, ref.Slug), c.Rule.PanelId, c.Rule.OrgId), nil + return fmt.Sprintf(urlFormat, models.GetFullDashboardUrl(ref.Uid, ref.Slug), c.Rule.PanelId, c.Rule.OrgId), nil } // GetNewState returns the new state from the alert rule evaluation -func (c *EvalContext) GetNewState() m.AlertStateType { +func (c *EvalContext) GetNewState() models.AlertStateType { ns := getNewStateInternal(c) - if ns != m.AlertStateAlerting || c.Rule.For == 0 { + if ns != models.AlertStateAlerting || c.Rule.For == 0 { return ns } since := time.Since(c.Rule.LastStateChange) - if c.PrevAlertState == m.AlertStatePending && since > c.Rule.For { - return m.AlertStateAlerting + if c.PrevAlertState == models.AlertStatePending && since > c.Rule.For { + return models.AlertStateAlerting } - if c.PrevAlertState == m.AlertStateAlerting { - return m.AlertStateAlerting + if c.PrevAlertState == models.AlertStateAlerting { + return models.AlertStateAlerting } - return m.AlertStatePending + return models.AlertStatePending } -func getNewStateInternal(c *EvalContext) m.AlertStateType { +func getNewStateInternal(c *EvalContext) models.AlertStateType { if c.Error != nil { c.log.Error("Alert Rule Result Error", "ruleId", c.Rule.Id, @@ -145,14 +145,14 @@ func getNewStateInternal(c *EvalContext) m.AlertStateType { "error", c.Error, "changing state to", c.Rule.ExecutionErrorState.ToAlertState()) - if c.Rule.ExecutionErrorState == m.ExecutionErrorKeepState { + if c.Rule.ExecutionErrorState == models.ExecutionErrorKeepState { return c.PrevAlertState } return c.Rule.ExecutionErrorState.ToAlertState() } if c.Firing { - return m.AlertStateAlerting + return models.AlertStateAlerting } if c.NoDataFound { @@ -161,11 +161,11 @@ func getNewStateInternal(c *EvalContext) m.AlertStateType { "name", c.Rule.Name, "changing state to", c.Rule.NoDataState.ToAlertState()) - if c.Rule.NoDataState == m.NoDataKeepState { + if c.Rule.NoDataState == models.NoDataKeepState { return c.PrevAlertState } return c.Rule.NoDataState.ToAlertState() } - return m.AlertStateOK + return models.AlertStateOK } diff --git a/pkg/services/alerting/extractor.go b/pkg/services/alerting/extractor.go index c3fcc01ad55e..6bf5e786c198 100644 --- a/pkg/services/alerting/extractor.go +++ b/pkg/services/alerting/extractor.go @@ -8,19 +8,19 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) // DashAlertExtractor extracts alerts from the dashboard json type DashAlertExtractor struct { - User *m.SignedInUser - Dash *m.Dashboard + User *models.SignedInUser + Dash *models.Dashboard OrgID int64 log log.Logger } // NewDashAlertExtractor returns a new DashAlertExtractor -func NewDashAlertExtractor(dash *m.Dashboard, orgID int64, user *m.SignedInUser) *DashAlertExtractor { +func NewDashAlertExtractor(dash *models.Dashboard, orgID int64, user *models.SignedInUser) *DashAlertExtractor { return &DashAlertExtractor{ User: user, Dash: dash, @@ -29,9 +29,9 @@ func NewDashAlertExtractor(dash *m.Dashboard, orgID int64, user *m.SignedInUser) } } -func (e *DashAlertExtractor) lookupDatasourceID(dsName string) (*m.DataSource, error) { +func (e *DashAlertExtractor) lookupDatasourceID(dsName string) (*models.DataSource, error) { if dsName == "" { - query := &m.GetDataSourcesQuery{OrgId: e.OrgID} + query := &models.GetDataSourcesQuery{OrgId: e.OrgID} if err := bus.Dispatch(query); err != nil { return nil, err } @@ -42,7 +42,7 @@ func (e *DashAlertExtractor) lookupDatasourceID(dsName string) (*m.DataSource, e } } } else { - query := &m.GetDataSourceByNameQuery{Name: dsName, OrgId: e.OrgID} + query := &models.GetDataSourceByNameQuery{Name: dsName, OrgId: e.OrgID} if err := bus.Dispatch(query); err != nil { return nil, err } @@ -73,8 +73,8 @@ func copyJSON(in *simplejson.Json) (*simplejson.Json, error) { return simplejson.NewJson(rawJSON) } -func (e *DashAlertExtractor) getAlertFromPanels(jsonWithPanels *simplejson.Json, validateAlertFunc func(*m.Alert) bool) ([]*m.Alert, error) { - alerts := make([]*m.Alert, 0) +func (e *DashAlertExtractor) getAlertFromPanels(jsonWithPanels *simplejson.Json, validateAlertFunc func(*models.Alert) bool) ([]*models.Alert, error) { + alerts := make([]*models.Alert, 0) for _, panelObj := range jsonWithPanels.Get("panels").MustArray() { panel := simplejson.NewFromAny(panelObj) @@ -124,7 +124,7 @@ func (e *DashAlertExtractor) getAlertFromPanels(jsonWithPanels *simplejson.Json, } } - alert := &m.Alert{ + alert := &models.Alert{ DashboardId: e.Dash.Id, OrgId: e.OrgID, PanelId: panelID, @@ -161,9 +161,9 @@ func (e *DashAlertExtractor) getAlertFromPanels(jsonWithPanels *simplejson.Json, return nil, ValidationError{Reason: fmt.Sprintf("Data source used by alert rule not found, alertName=%v, datasource=%s", alert.Name, dsName)} } - dsFilterQuery := m.DatasourcesPermissionFilterQuery{ + dsFilterQuery := models.DatasourcesPermissionFilterQuery{ User: e.User, - Datasources: []*m.DataSource{datasource}, + Datasources: []*models.DataSource{datasource}, } if err := bus.Dispatch(&dsFilterQuery); err != nil { @@ -172,7 +172,7 @@ func (e *DashAlertExtractor) getAlertFromPanels(jsonWithPanels *simplejson.Json, } } else { if len(dsFilterQuery.Result) == 0 { - return nil, m.ErrDataSourceAccessDenied + return nil, models.ErrDataSourceAccessDenied } } @@ -203,22 +203,22 @@ func (e *DashAlertExtractor) getAlertFromPanels(jsonWithPanels *simplejson.Json, return alerts, nil } -func validateAlertRule(alert *m.Alert) bool { +func validateAlertRule(alert *models.Alert) bool { return alert.ValidToSave() } // GetAlerts extracts alerts from the dashboard json and does full validation on the alert json data -func (e *DashAlertExtractor) GetAlerts() ([]*m.Alert, error) { +func (e *DashAlertExtractor) GetAlerts() ([]*models.Alert, error) { return e.extractAlerts(validateAlertRule) } -func (e *DashAlertExtractor) extractAlerts(validateFunc func(alert *m.Alert) bool) ([]*m.Alert, error) { +func (e *DashAlertExtractor) extractAlerts(validateFunc func(alert *models.Alert) bool) ([]*models.Alert, error) { dashboardJSON, err := copyJSON(e.Dash.Data) if err != nil { return nil, err } - alerts := make([]*m.Alert, 0) + alerts := make([]*models.Alert, 0) // We extract alerts from rows to be backwards compatible // with the old dashboard json model. @@ -249,6 +249,6 @@ func (e *DashAlertExtractor) extractAlerts(validateFunc func(alert *m.Alert) boo // ValidateAlerts validates alerts in the dashboard json but does not require a valid dashboard id // in the first validation pass func (e *DashAlertExtractor) ValidateAlerts() error { - _, err := e.extractAlerts(func(alert *m.Alert) bool { return alert.OrgId != 0 && alert.PanelId != 0 }) + _, err := e.extractAlerts(func(alert *models.Alert) bool { return alert.OrgId != 0 && alert.PanelId != 0 }) return err } diff --git a/pkg/services/alerting/extractor_test.go b/pkg/services/alerting/extractor_test.go index 9c689fec921b..716ff746cd84 100644 --- a/pkg/services/alerting/extractor_test.go +++ b/pkg/services/alerting/extractor_test.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/sqlstore" . "github.com/smartystreets/goconvey/convey" ) @@ -21,17 +21,17 @@ func TestAlertRuleExtraction(t *testing.T) { }) // mock data - defaultDs := &m.DataSource{Id: 12, OrgId: 1, Name: "I am default", IsDefault: true} - graphite2Ds := &m.DataSource{Id: 15, OrgId: 1, Name: "graphite2"} - influxDBDs := &m.DataSource{Id: 16, OrgId: 1, Name: "InfluxDB"} - prom := &m.DataSource{Id: 17, OrgId: 1, Name: "Prometheus"} + defaultDs := &models.DataSource{Id: 12, OrgId: 1, Name: "I am default", IsDefault: true} + graphite2Ds := &models.DataSource{Id: 15, OrgId: 1, Name: "graphite2"} + influxDBDs := &models.DataSource{Id: 16, OrgId: 1, Name: "InfluxDB"} + prom := &models.DataSource{Id: 17, OrgId: 1, Name: "Prometheus"} - bus.AddHandler("test", func(query *m.GetDataSourcesQuery) error { - query.Result = []*m.DataSource{defaultDs, graphite2Ds} + bus.AddHandler("test", func(query *models.GetDataSourcesQuery) error { + query.Result = []*models.DataSource{defaultDs, graphite2Ds} return nil }) - bus.AddHandler("test", func(query *m.GetDataSourceByNameQuery) error { + bus.AddHandler("test", func(query *models.GetDataSourceByNameQuery) error { if query.Name == defaultDs.Name { query.Result = defaultDs } @@ -55,7 +55,7 @@ func TestAlertRuleExtraction(t *testing.T) { dashJson, err := simplejson.NewJson(json) So(err, ShouldBeNil) - dash := m.NewDashboardFromJson(dashJson) + dash := models.NewDashboardFromJson(dashJson) getTarget := func(j *simplejson.Json) string { rowObj := j.Get("rows").MustArray()[0] @@ -84,7 +84,7 @@ func TestAlertRuleExtraction(t *testing.T) { dashJson, err := simplejson.NewJson(json) So(err, ShouldBeNil) - dash := m.NewDashboardFromJson(dashJson) + dash := models.NewDashboardFromJson(dashJson) extractor := NewDashAlertExtractor(dash, 1, nil) alerts, err := extractor.GetAlerts() @@ -152,7 +152,7 @@ func TestAlertRuleExtraction(t *testing.T) { dashJson, err := simplejson.NewJson(panelWithoutId) So(err, ShouldBeNil) - dash := m.NewDashboardFromJson(dashJson) + dash := models.NewDashboardFromJson(dashJson) extractor := NewDashAlertExtractor(dash, 1, nil) _, err = extractor.GetAlerts() @@ -168,7 +168,7 @@ func TestAlertRuleExtraction(t *testing.T) { dashJson, err := simplejson.NewJson(panelWithIdZero) So(err, ShouldBeNil) - dash := m.NewDashboardFromJson(dashJson) + dash := models.NewDashboardFromJson(dashJson) extractor := NewDashAlertExtractor(dash, 1, nil) _, err = extractor.GetAlerts() @@ -184,7 +184,7 @@ func TestAlertRuleExtraction(t *testing.T) { dashJson, err := simplejson.NewJson(json) So(err, ShouldBeNil) - dash := m.NewDashboardFromJson(dashJson) + dash := models.NewDashboardFromJson(dashJson) extractor := NewDashAlertExtractor(dash, 1, nil) alerts, err := extractor.GetAlerts() @@ -200,10 +200,10 @@ func TestAlertRuleExtraction(t *testing.T) { Convey("Alert notifications are in DB", func() { sqlstore.InitTestDB(t) - firstNotification := m.CreateAlertNotificationCommand{Uid: "notifier1", OrgId: 1, Name: "1"} + firstNotification := models.CreateAlertNotificationCommand{Uid: "notifier1", OrgId: 1, Name: "1"} err = sqlstore.CreateAlertNotificationCommand(&firstNotification) So(err, ShouldBeNil) - secondNotification := m.CreateAlertNotificationCommand{Uid: "notifier2", OrgId: 1, Name: "2"} + secondNotification := models.CreateAlertNotificationCommand{Uid: "notifier2", OrgId: 1, Name: "2"} err = sqlstore.CreateAlertNotificationCommand(&secondNotification) So(err, ShouldBeNil) @@ -213,7 +213,7 @@ func TestAlertRuleExtraction(t *testing.T) { dashJson, err := simplejson.NewJson(json) So(err, ShouldBeNil) - dash := m.NewDashboardFromJson(dashJson) + dash := models.NewDashboardFromJson(dashJson) extractor := NewDashAlertExtractor(dash, 1, nil) alerts, err := extractor.GetAlerts() @@ -243,7 +243,7 @@ func TestAlertRuleExtraction(t *testing.T) { dashJson, err := simplejson.NewJson(json) So(err, ShouldBeNil) - dash := m.NewDashboardFromJson(dashJson) + dash := models.NewDashboardFromJson(dashJson) extractor := NewDashAlertExtractor(dash, 1, nil) alerts, err := extractor.GetAlerts() @@ -263,7 +263,7 @@ func TestAlertRuleExtraction(t *testing.T) { dashJSON, err := simplejson.NewJson(json) So(err, ShouldBeNil) - dash := m.NewDashboardFromJson(dashJSON) + dash := models.NewDashboardFromJson(dashJSON) extractor := NewDashAlertExtractor(dash, 1, nil) err = extractor.ValidateAlerts() diff --git a/pkg/services/alerting/notifier.go b/pkg/services/alerting/notifier.go index 8c2ac839e439..a2824da4a67c 100644 --- a/pkg/services/alerting/notifier.go +++ b/pkg/services/alerting/notifier.go @@ -8,10 +8,9 @@ import ( "github.com/grafana/grafana/pkg/components/imguploader" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/rendering" "github.com/grafana/grafana/pkg/setting" - - m "github.com/grafana/grafana/pkg/models" ) type NotifierPlugin struct { @@ -73,7 +72,7 @@ func (n *notificationService) sendAndMarkAsComplete(evalContext *EvalContext, no return nil } - cmd := &m.SetAlertNotificationStateToCompleteCommand{ + cmd := &models.SetAlertNotificationStateToCompleteCommand{ Id: notifierState.state.Id, Version: notifierState.state.Version, } @@ -83,14 +82,14 @@ func (n *notificationService) sendAndMarkAsComplete(evalContext *EvalContext, no func (n *notificationService) sendNotification(evalContext *EvalContext, notifierState *notifierState) error { if !evalContext.IsTestRun { - setPendingCmd := &m.SetAlertNotificationStateToPendingCommand{ + setPendingCmd := &models.SetAlertNotificationStateToPendingCommand{ Id: notifierState.state.Id, Version: notifierState.state.Version, AlertRuleStateUpdatedVersion: evalContext.Rule.StateChanges, } err := bus.DispatchCtx(evalContext.Ctx, setPendingCmd) - if err == m.ErrAlertNotificationStateVersionConflict { + if err == models.ErrAlertNotificationStateVersionConflict { return nil } @@ -128,7 +127,7 @@ func (n *notificationService) uploadImage(context *EvalContext) (err error) { Height: 500, Timeout: setting.AlertingEvaluationTimeout, OrgId: context.Rule.OrgId, - OrgRole: m.ROLE_ADMIN, + OrgRole: models.ROLE_ADMIN, ConcurrentLimit: setting.AlertingRenderLimit, } @@ -158,7 +157,7 @@ func (n *notificationService) uploadImage(context *EvalContext) (err error) { } func (n *notificationService) getNeededNotifiers(orgId int64, notificationUids []string, evalContext *EvalContext) (notifierStateSlice, error) { - query := &m.GetAlertNotificationsWithUidToSendQuery{OrgId: orgId, Uids: notificationUids} + query := &models.GetAlertNotificationsWithUidToSendQuery{OrgId: orgId, Uids: notificationUids} if err := bus.Dispatch(query); err != nil { return nil, err @@ -172,7 +171,7 @@ func (n *notificationService) getNeededNotifiers(orgId int64, notificationUids [ continue } - query := &m.GetOrCreateNotificationStateQuery{ + query := &models.GetOrCreateNotificationStateQuery{ NotifierId: notification.Id, AlertId: evalContext.Rule.Id, OrgId: evalContext.Rule.OrgId, @@ -196,7 +195,7 @@ func (n *notificationService) getNeededNotifiers(orgId int64, notificationUids [ } // InitNotifier instantiate a new notifier based on the model -func InitNotifier(model *m.AlertNotification) (Notifier, error) { +func InitNotifier(model *models.AlertNotification) (Notifier, error) { notifierPlugin, found := notifierFactories[model.Type] if !found { return nil, errors.New("Unsupported notification type") @@ -205,7 +204,7 @@ func InitNotifier(model *m.AlertNotification) (Notifier, error) { return notifierPlugin.Factory(model) } -type NotifierFactory func(notification *m.AlertNotification) (Notifier, error) +type NotifierFactory func(notification *models.AlertNotification) (Notifier, error) var notifierFactories = make(map[string]*NotifierPlugin) diff --git a/pkg/services/alerting/notifiers/alertmanager.go b/pkg/services/alerting/notifiers/alertmanager.go index 9febe42505be..b90f9e65792c 100644 --- a/pkg/services/alerting/notifiers/alertmanager.go +++ b/pkg/services/alerting/notifiers/alertmanager.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -27,7 +27,7 @@ func init() { }) } -func NewAlertmanagerNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewAlertmanagerNotifier(model *models.AlertNotification) (alerting.Notifier, error) { url := model.Settings.Get("url").MustString() if url == "" { return nil, alerting.ValidationError{Reason: "Could not find url property in settings"} @@ -46,24 +46,24 @@ type AlertmanagerNotifier struct { log log.Logger } -func (this *AlertmanagerNotifier) ShouldNotify(ctx context.Context, evalContext *alerting.EvalContext, notificationState *m.AlertNotificationState) bool { +func (this *AlertmanagerNotifier) ShouldNotify(ctx context.Context, evalContext *alerting.EvalContext, notificationState *models.AlertNotificationState) bool { this.log.Debug("Should notify", "ruleId", evalContext.Rule.Id, "state", evalContext.Rule.State, "previousState", evalContext.PrevAlertState) // Do not notify when we become OK for the first time. - if (evalContext.PrevAlertState == m.AlertStatePending) && (evalContext.Rule.State == m.AlertStateOK) { + if (evalContext.PrevAlertState == models.AlertStatePending) && (evalContext.Rule.State == models.AlertStateOK) { return false } // Notify on Alerting -> OK to resolve before alertmanager timeout. - if (evalContext.PrevAlertState == m.AlertStateAlerting) && (evalContext.Rule.State == m.AlertStateOK) { + if (evalContext.PrevAlertState == models.AlertStateAlerting) && (evalContext.Rule.State == models.AlertStateOK) { return true } - return evalContext.Rule.State == m.AlertStateAlerting + return evalContext.Rule.State == models.AlertStateAlerting } func (this *AlertmanagerNotifier) createAlert(evalContext *alerting.EvalContext, match *alerting.EvalMatch, ruleUrl string) *simplejson.Json { alertJSON := simplejson.New() alertJSON.Set("startsAt", evalContext.StartTime.UTC().Format(time.RFC3339)) - if evalContext.Rule.State == m.AlertStateOK { + if evalContext.Rule.State == models.AlertStateOK { alertJSON.Set("endsAt", time.Now().UTC().Format(time.RFC3339)) } alertJSON.Set("generatorURL", ruleUrl) @@ -128,7 +128,7 @@ func (this *AlertmanagerNotifier) Notify(evalContext *alerting.EvalContext) erro bodyJSON := simplejson.NewFromAny(alerts) body, _ := bodyJSON.MarshalJSON() - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: this.Url + "/api/v1/alerts", HttpMethod: "POST", Body: string(body), diff --git a/pkg/services/alerting/notifiers/alertmanager_test.go b/pkg/services/alerting/notifiers/alertmanager_test.go index 9197926035ea..acf039fbf68e 100644 --- a/pkg/services/alerting/notifiers/alertmanager_test.go +++ b/pkg/services/alerting/notifiers/alertmanager_test.go @@ -6,36 +6,37 @@ import ( "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/services/alerting" . "github.com/smartystreets/goconvey/convey" ) func TestWhenAlertManagerShouldNotify(t *testing.T) { tcs := []struct { - prevState m.AlertStateType - newState m.AlertStateType + prevState models.AlertStateType + newState models.AlertStateType expect bool }{ { - prevState: m.AlertStatePending, - newState: m.AlertStateOK, + prevState: models.AlertStatePending, + newState: models.AlertStateOK, expect: false, }, { - prevState: m.AlertStateAlerting, - newState: m.AlertStateOK, + prevState: models.AlertStateAlerting, + newState: models.AlertStateOK, expect: true, }, { - prevState: m.AlertStateOK, - newState: m.AlertStatePending, + prevState: models.AlertStateOK, + newState: models.AlertStatePending, expect: false, }, { - prevState: m.AlertStateUnknown, - newState: m.AlertStatePending, + prevState: models.AlertStateUnknown, + newState: models.AlertStatePending, expect: false, }, } @@ -48,7 +49,7 @@ func TestWhenAlertManagerShouldNotify(t *testing.T) { evalContext.Rule.State = tc.newState - res := am.ShouldNotify(context.TODO(), evalContext, &m.AlertNotificationState{}) + res := am.ShouldNotify(context.TODO(), evalContext, &models.AlertNotificationState{}) if res != tc.expect { t.Errorf("got %v expected %v", res, tc.expect) } @@ -63,7 +64,7 @@ func TestAlertmanagerNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "alertmanager", Type: "alertmanager", Settings: settingsJSON, @@ -77,7 +78,7 @@ func TestAlertmanagerNotifier(t *testing.T) { json := `{ "url": "http://127.0.0.1:9093/" }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "alertmanager", Type: "alertmanager", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/dingding.go b/pkg/services/alerting/notifiers/dingding.go index 0aa2ba078f37..45ce24c9aaa1 100644 --- a/pkg/services/alerting/notifiers/dingding.go +++ b/pkg/services/alerting/notifiers/dingding.go @@ -8,7 +8,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -36,7 +36,7 @@ func init() { } -func NewDingDingNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewDingDingNotifier(model *models.AlertNotification) (alerting.Notifier, error) { url := model.Settings.Get("url").MustString() if url == "" { return nil, alerting.ValidationError{Reason: "Could not find url property in settings"} @@ -129,7 +129,7 @@ func (this *DingDingNotifier) Notify(evalContext *alerting.EvalContext) error { return err } - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: this.Url, Body: string(body), } diff --git a/pkg/services/alerting/notifiers/dingding_test.go b/pkg/services/alerting/notifiers/dingding_test.go index f89bf6382ce9..7d645d7efb62 100644 --- a/pkg/services/alerting/notifiers/dingding_test.go +++ b/pkg/services/alerting/notifiers/dingding_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -14,7 +14,7 @@ func TestDingDingNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "dingding_testing", Type: "dingding", Settings: settingsJSON, @@ -28,7 +28,7 @@ func TestDingDingNotifier(t *testing.T) { json := `{ "url": "https://www.google.com" }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "dingding_testing", Type: "dingding", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/discord.go b/pkg/services/alerting/notifiers/discord.go index 6ed422b1cbb0..9933ad5e5871 100644 --- a/pkg/services/alerting/notifiers/discord.go +++ b/pkg/services/alerting/notifiers/discord.go @@ -11,7 +11,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/setting" ) @@ -32,7 +32,7 @@ func init() { }) } -func NewDiscordNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewDiscordNotifier(model *models.AlertNotification) (alerting.Notifier, error) { url := model.Settings.Get("url").MustString() if url == "" { return nil, alerting.ValidationError{Reason: "Could not find webhook url property in settings"} @@ -111,7 +111,7 @@ func (this *DiscordNotifier) Notify(evalContext *alerting.EvalContext) error { json, _ := bodyJSON.MarshalJSON() - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: this.WebhookURL, HttpMethod: "POST", ContentType: "application/json", @@ -135,7 +135,7 @@ func (this *DiscordNotifier) Notify(evalContext *alerting.EvalContext) error { return nil } -func (this *DiscordNotifier) embedImage(cmd *m.SendWebhookSync, imagePath string, existingJSONBody []byte) error { +func (this *DiscordNotifier) embedImage(cmd *models.SendWebhookSync, imagePath string, existingJSONBody []byte) error { f, err := os.Open(imagePath) defer f.Close() if err != nil { diff --git a/pkg/services/alerting/notifiers/discord_test.go b/pkg/services/alerting/notifiers/discord_test.go index fe925aab362e..dfc6bbe9aee0 100644 --- a/pkg/services/alerting/notifiers/discord_test.go +++ b/pkg/services/alerting/notifiers/discord_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestDiscordNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "discord_testing", Type: "discord", Settings: settingsJSON, @@ -33,7 +33,7 @@ func TestDiscordNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "discord_testing", Type: "discord", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/email.go b/pkg/services/alerting/notifiers/email.go index b3f465a2b80c..61b7b11d893c 100644 --- a/pkg/services/alerting/notifiers/email.go +++ b/pkg/services/alerting/notifiers/email.go @@ -6,7 +6,8 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/setting" ) @@ -35,7 +36,7 @@ type EmailNotifier struct { log log.Logger } -func NewEmailNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewEmailNotifier(model *models.AlertNotification) (alerting.Notifier, error) { addressesString := model.Settings.Get("addresses").MustString() if addressesString == "" { @@ -72,8 +73,8 @@ func (this *EmailNotifier) Notify(evalContext *alerting.EvalContext) error { error = evalContext.Error.Error() } - cmd := &m.SendEmailCommandSync{ - SendEmailCommand: m.SendEmailCommand{ + cmd := &models.SendEmailCommandSync{ + SendEmailCommand: models.SendEmailCommand{ Subject: evalContext.GetNotificationTitle(), Data: map[string]interface{}{ "Title": evalContext.GetNotificationTitle(), diff --git a/pkg/services/alerting/notifiers/email_test.go b/pkg/services/alerting/notifiers/email_test.go index 9750cbc2833c..b0c57f2f254d 100644 --- a/pkg/services/alerting/notifiers/email_test.go +++ b/pkg/services/alerting/notifiers/email_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestEmailNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "email", Settings: settingsJSON, @@ -33,7 +33,7 @@ func TestEmailNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "email", Settings: settingsJSON, @@ -57,7 +57,7 @@ func TestEmailNotifier(t *testing.T) { settingsJSON, err := simplejson.NewJson([]byte(json)) So(err, ShouldBeNil) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "email", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/googlechat.go b/pkg/services/alerting/notifiers/googlechat.go index 41f3503640cb..c00089e0dc57 100644 --- a/pkg/services/alerting/notifiers/googlechat.go +++ b/pkg/services/alerting/notifiers/googlechat.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/setting" ) @@ -29,7 +29,7 @@ func init() { }) } -func NewGoogleChatNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewGoogleChatNotifier(model *models.AlertNotification) (alerting.Notifier, error) { url := model.Settings.Get("url").MustString() if url == "" { return nil, alerting.ValidationError{Reason: "Could not find url property in settings"} @@ -199,7 +199,7 @@ func (this *GoogleChatNotifier) Notify(evalContext *alerting.EvalContext) error } body, _ := json.Marshal(res1D) - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: this.Url, HttpMethod: "POST", HttpHeader: headers, diff --git a/pkg/services/alerting/notifiers/googlechat_test.go b/pkg/services/alerting/notifiers/googlechat_test.go index 1fdce878926f..5368eb63c96b 100644 --- a/pkg/services/alerting/notifiers/googlechat_test.go +++ b/pkg/services/alerting/notifiers/googlechat_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestGoogleChatNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "googlechat", Settings: settingsJSON, @@ -33,7 +33,7 @@ func TestGoogleChatNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "googlechat", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/hipchat_test.go b/pkg/services/alerting/notifiers/hipchat_test.go index 1597be12eb8b..57ad03ed7c21 100644 --- a/pkg/services/alerting/notifiers/hipchat_test.go +++ b/pkg/services/alerting/notifiers/hipchat_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestHipChatNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "hipchat", Settings: settingsJSON, @@ -33,7 +33,7 @@ func TestHipChatNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "hipchat", Settings: settingsJSON, @@ -59,7 +59,7 @@ func TestHipChatNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "hipchat", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/kafka.go b/pkg/services/alerting/notifiers/kafka.go index d7da05499b75..168b1646b16b 100644 --- a/pkg/services/alerting/notifiers/kafka.go +++ b/pkg/services/alerting/notifiers/kafka.go @@ -8,7 +8,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -32,7 +32,7 @@ func init() { }) } -func NewKafkaNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewKafkaNotifier(model *models.AlertNotification) (alerting.Notifier, error) { endpoint := model.Settings.Get("kafkaRestProxy").MustString() if endpoint == "" { return nil, alerting.ValidationError{Reason: "Could not find kafka rest proxy endpoint property in settings"} @@ -101,7 +101,7 @@ func (this *KafkaNotifier) Notify(evalContext *alerting.EvalContext) error { topicUrl := this.Endpoint + "/topics/" + this.Topic - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: topicUrl, Body: string(body), HttpMethod: "POST", diff --git a/pkg/services/alerting/notifiers/kafka_test.go b/pkg/services/alerting/notifiers/kafka_test.go index 045976cb14ba..03a343835e15 100644 --- a/pkg/services/alerting/notifiers/kafka_test.go +++ b/pkg/services/alerting/notifiers/kafka_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestKafkaNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "kafka_testing", Type: "kafka", Settings: settingsJSON, @@ -34,7 +34,7 @@ func TestKafkaNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "kafka_testing", Type: "kafka", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/line.go b/pkg/services/alerting/notifiers/line.go index edbec373becd..d8bf70f8b9c9 100644 --- a/pkg/services/alerting/notifiers/line.go +++ b/pkg/services/alerting/notifiers/line.go @@ -6,7 +6,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -32,7 +32,7 @@ const ( lineNotifyUrl string = "https://notify-api.line.me/api/notify" ) -func NewLINENotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewLINENotifier(model *models.AlertNotification) (alerting.Notifier, error) { token := model.Settings.Get("token").MustString() if token == "" { return nil, alerting.ValidationError{Reason: "Could not find token in settings"} @@ -56,7 +56,7 @@ func (this *LineNotifier) Notify(evalContext *alerting.EvalContext) error { var err error switch evalContext.Rule.State { - case m.AlertStateAlerting: + case models.AlertStateAlerting: err = this.createAlert(evalContext) } return err @@ -79,7 +79,7 @@ func (this *LineNotifier) createAlert(evalContext *alerting.EvalContext) error { form.Add("imageFullsize", evalContext.ImagePublicUrl) } - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: lineNotifyUrl, HttpMethod: "POST", HttpHeader: map[string]string{ diff --git a/pkg/services/alerting/notifiers/line_test.go b/pkg/services/alerting/notifiers/line_test.go index 6630665e9924..69082d0e066e 100644 --- a/pkg/services/alerting/notifiers/line_test.go +++ b/pkg/services/alerting/notifiers/line_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -14,7 +14,7 @@ func TestLineNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "line_testing", Type: "line", Settings: settingsJSON, @@ -30,7 +30,7 @@ func TestLineNotifier(t *testing.T) { "token": "abcdefgh0123456789" }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "line_testing", Type: "line", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/opsgenie.go b/pkg/services/alerting/notifiers/opsgenie.go index 84242ea97691..23dd453fe92e 100644 --- a/pkg/services/alerting/notifiers/opsgenie.go +++ b/pkg/services/alerting/notifiers/opsgenie.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -44,7 +44,7 @@ var ( opsgenieAlertURL = "https://api.opsgenie.com/v2/alerts" ) -func NewOpsGenieNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewOpsGenieNotifier(model *models.AlertNotification) (alerting.Notifier, error) { autoClose := model.Settings.Get("autoClose").MustBool(true) apiKey := model.Settings.Get("apiKey").MustString() apiUrl := model.Settings.Get("apiUrl").MustString() @@ -76,11 +76,11 @@ func (this *OpsGenieNotifier) Notify(evalContext *alerting.EvalContext) error { var err error switch evalContext.Rule.State { - case m.AlertStateOK: + case models.AlertStateOK: if this.AutoClose { err = this.closeAlert(evalContext) } - case m.AlertStateAlerting: + case models.AlertStateAlerting: err = this.createAlert(evalContext) } return err @@ -115,7 +115,7 @@ func (this *OpsGenieNotifier) createAlert(evalContext *alerting.EvalContext) err bodyJSON.Set("details", details) body, _ := bodyJSON.MarshalJSON() - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: this.ApiUrl, Body: string(body), HttpMethod: "POST", @@ -139,7 +139,7 @@ func (this *OpsGenieNotifier) closeAlert(evalContext *alerting.EvalContext) erro bodyJSON.Set("source", "Grafana") body, _ := bodyJSON.MarshalJSON() - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: fmt.Sprintf("%s/alertId-%d/close?identifierType=alias", this.ApiUrl, evalContext.Rule.Id), Body: string(body), HttpMethod: "POST", diff --git a/pkg/services/alerting/notifiers/opsgenie_test.go b/pkg/services/alerting/notifiers/opsgenie_test.go index 9dcb9f3c600e..e4954ed904af 100644 --- a/pkg/services/alerting/notifiers/opsgenie_test.go +++ b/pkg/services/alerting/notifiers/opsgenie_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestOpsGenieNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "opsgenie_testing", Type: "opsgenie", Settings: settingsJSON, @@ -33,7 +33,7 @@ func TestOpsGenieNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "opsgenie_testing", Type: "opsgenie", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/pagerduty.go b/pkg/services/alerting/notifiers/pagerduty.go index ab2a36fd86b2..2b60058ecd93 100644 --- a/pkg/services/alerting/notifiers/pagerduty.go +++ b/pkg/services/alerting/notifiers/pagerduty.go @@ -10,7 +10,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -43,7 +43,7 @@ var ( pagerdutyEventApiUrl = "https://events.pagerduty.com/v2/enqueue" ) -func NewPagerdutyNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewPagerdutyNotifier(model *models.AlertNotification) (alerting.Notifier, error) { autoResolve := model.Settings.Get("autoResolve").MustBool(false) key := model.Settings.Get("integrationKey").MustString() if key == "" { @@ -67,13 +67,13 @@ type PagerdutyNotifier struct { func (this *PagerdutyNotifier) Notify(evalContext *alerting.EvalContext) error { - if evalContext.Rule.State == m.AlertStateOK && !this.AutoResolve { + if evalContext.Rule.State == models.AlertStateOK && !this.AutoResolve { this.log.Info("Not sending a trigger to Pagerduty", "state", evalContext.Rule.State, "auto resolve", this.AutoResolve) return nil } eventType := "trigger" - if evalContext.Rule.State == m.AlertStateOK { + if evalContext.Rule.State == models.AlertStateOK { eventType = "resolve" } customData := triggMetrString @@ -122,7 +122,7 @@ func (this *PagerdutyNotifier) Notify(evalContext *alerting.EvalContext) error { body, _ := bodyJSON.MarshalJSON() - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: pagerdutyEventApiUrl, Body: string(body), HttpMethod: "POST", diff --git a/pkg/services/alerting/notifiers/pagerduty_test.go b/pkg/services/alerting/notifiers/pagerduty_test.go index 1d2eeec4a522..1698ec7605ac 100644 --- a/pkg/services/alerting/notifiers/pagerduty_test.go +++ b/pkg/services/alerting/notifiers/pagerduty_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -15,7 +15,7 @@ func TestPagerdutyNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "pageduty_testing", Type: "pagerduty", Settings: settingsJSON, @@ -29,7 +29,7 @@ func TestPagerdutyNotifier(t *testing.T) { json := `{ "integrationKey": "abcdefgh0123456789" }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "pagerduty_testing", Type: "pagerduty", Settings: settingsJSON, @@ -53,7 +53,7 @@ func TestPagerdutyNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "pagerduty_testing", Type: "pagerduty", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/pushover.go b/pkg/services/alerting/notifiers/pushover.go index 0d23bbf6fb3c..a54fb1ee084d 100644 --- a/pkg/services/alerting/notifiers/pushover.go +++ b/pkg/services/alerting/notifiers/pushover.go @@ -10,7 +10,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -95,7 +95,7 @@ func init() { }) } -func NewPushoverNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewPushoverNotifier(model *models.AlertNotification) (alerting.Notifier, error) { userKey := model.Settings.Get("userKey").MustString() apiToken := model.Settings.Get("apiToken").MustString() device := model.Settings.Get("device").MustString() @@ -169,7 +169,7 @@ func (this *PushoverNotifier) Notify(evalContext *alerting.EvalContext) error { return err } - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: PUSHOVER_ENDPOINT, HttpMethod: "POST", HttpHeader: headers, @@ -248,7 +248,7 @@ func (this *PushoverNotifier) genPushoverBody(evalContext *alerting.EvalContext, // Add sound sound := this.AlertingSound - if evalContext.Rule.State == m.AlertStateOK { + if evalContext.Rule.State == models.AlertStateOK { sound = this.OkSound } if sound != "default" { diff --git a/pkg/services/alerting/notifiers/pushover_test.go b/pkg/services/alerting/notifiers/pushover_test.go index 5228491cccd5..f862a500618a 100644 --- a/pkg/services/alerting/notifiers/pushover_test.go +++ b/pkg/services/alerting/notifiers/pushover_test.go @@ -2,12 +2,13 @@ package notifiers import ( "context" - "github.com/grafana/grafana/pkg/services/alerting" "strings" "testing" + "github.com/grafana/grafana/pkg/services/alerting" + "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -19,7 +20,7 @@ func TestPushoverNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "Pushover", Type: "pushover", Settings: settingsJSON, @@ -40,7 +41,7 @@ func TestPushoverNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "Pushover", Type: "pushover", Settings: settingsJSON, @@ -73,7 +74,7 @@ func TestGenPushoverBody(t *testing.T) { Convey("When alert is firing - should use siren sound", func() { evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ - State: m.AlertStateAlerting, + State: models.AlertStateAlerting, }) _, pushoverBody, err := notifier.genPushoverBody(evalContext, "", "") @@ -84,7 +85,7 @@ func TestGenPushoverBody(t *testing.T) { Convey("When alert is ok - should use success sound", func() { evalContext := alerting.NewEvalContext(context.Background(), &alerting.Rule{ - State: m.AlertStateOK, + State: models.AlertStateOK, }) _, pushoverBody, err := notifier.genPushoverBody(evalContext, "", "") diff --git a/pkg/services/alerting/notifiers/sensu.go b/pkg/services/alerting/notifiers/sensu.go index b018c53208e8..cad9fc2286a3 100644 --- a/pkg/services/alerting/notifiers/sensu.go +++ b/pkg/services/alerting/notifiers/sensu.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -44,7 +44,7 @@ func init() { } -func NewSensuNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewSensuNotifier(model *models.AlertNotification) (alerting.Notifier, error) { url := model.Settings.Get("url").MustString() if url == "" { return nil, alerting.ValidationError{Reason: "Could not find url property in settings"} @@ -117,7 +117,7 @@ func (this *SensuNotifier) Notify(evalContext *alerting.EvalContext) error { body, _ := bodyJSON.MarshalJSON() - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: this.Url, User: this.User, Password: this.Password, diff --git a/pkg/services/alerting/notifiers/sensu_test.go b/pkg/services/alerting/notifiers/sensu_test.go index 40e3b1e1cc31..40d39a5d1c3f 100644 --- a/pkg/services/alerting/notifiers/sensu_test.go +++ b/pkg/services/alerting/notifiers/sensu_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestSensuNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "sensu", Type: "sensu", Settings: settingsJSON, @@ -35,7 +35,7 @@ func TestSensuNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "sensu", Type: "sensu", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/slack.go b/pkg/services/alerting/notifiers/slack.go index 7754b7de71aa..117674448877 100644 --- a/pkg/services/alerting/notifiers/slack.go +++ b/pkg/services/alerting/notifiers/slack.go @@ -11,7 +11,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" "github.com/grafana/grafana/pkg/setting" ) @@ -99,7 +99,7 @@ func init() { } -func NewSlackNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewSlackNotifier(model *models.AlertNotification) (alerting.Notifier, error) { url := model.Settings.Get("url").MustString() if url == "" { return nil, alerting.ValidationError{Reason: "Could not find url property in settings"} @@ -171,7 +171,7 @@ func (this *SlackNotifier) Notify(evalContext *alerting.EvalContext) error { } message := this.Mention - if evalContext.Rule.State != m.AlertStateOK { //don't add message when going back to alert state ok. + if evalContext.Rule.State != models.AlertStateOK { //don't add message when going back to alert state ok. message += " " + evalContext.Rule.Message } image_url := "" @@ -212,7 +212,7 @@ func (this *SlackNotifier) Notify(evalContext *alerting.EvalContext) error { body["icon_url"] = this.IconUrl } data, _ := json.Marshal(&body) - cmd := &m.SendWebhookSync{Url: this.Url, Body: string(data)} + cmd := &models.SendWebhookSync{Url: this.Url, Body: string(data)} if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil { this.log.Error("Failed to send slack notification", "error", err, "webhook", this.Name) return err @@ -235,7 +235,7 @@ func SlackFileUpload(evalContext *alerting.EvalContext, log log.Logger, url stri if err != nil { return err } - cmd := &m.SendWebhookSync{Url: url, Body: uploadBody.String(), HttpHeader: headers, HttpMethod: "POST"} + cmd := &models.SendWebhookSync{Url: url, Body: uploadBody.String(), HttpHeader: headers, HttpMethod: "POST"} if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil { log.Error("Failed to upload slack image", "error", err, "webhook", "file.upload") return err diff --git a/pkg/services/alerting/notifiers/slack_test.go b/pkg/services/alerting/notifiers/slack_test.go index 17362bc850b6..7dceb12676c9 100644 --- a/pkg/services/alerting/notifiers/slack_test.go +++ b/pkg/services/alerting/notifiers/slack_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestSlackNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "slack", Settings: settingsJSON, @@ -33,7 +33,7 @@ func TestSlackNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "slack", Settings: settingsJSON, @@ -67,7 +67,7 @@ func TestSlackNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "slack", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/teams.go b/pkg/services/alerting/notifiers/teams.go index e33a93f8a0cf..57f5d6e91c04 100644 --- a/pkg/services/alerting/notifiers/teams.go +++ b/pkg/services/alerting/notifiers/teams.go @@ -5,7 +5,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -26,7 +26,7 @@ func init() { } -func NewTeamsNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewTeamsNotifier(model *models.AlertNotification) (alerting.Notifier, error) { url := model.Settings.Get("url").MustString() if url == "" { return nil, alerting.ValidationError{Reason: "Could not find url property in settings"} @@ -74,7 +74,7 @@ func (this *TeamsNotifier) Notify(evalContext *alerting.EvalContext) error { } message := "" - if evalContext.Rule.State != m.AlertStateOK { //don't add message when going back to alert state ok. + if evalContext.Rule.State != models.AlertStateOK { //don't add message when going back to alert state ok. message = evalContext.Rule.Message } @@ -126,7 +126,7 @@ func (this *TeamsNotifier) Notify(evalContext *alerting.EvalContext) error { } data, _ := json.Marshal(&body) - cmd := &m.SendWebhookSync{Url: this.Url, Body: string(data)} + cmd := &models.SendWebhookSync{Url: this.Url, Body: string(data)} if err := bus.DispatchCtx(evalContext.Ctx, cmd); err != nil { this.log.Error("Failed to send teams notification", "error", err, "webhook", this.Name) diff --git a/pkg/services/alerting/notifiers/teams_test.go b/pkg/services/alerting/notifiers/teams_test.go index a96473507363..1dd35c899605 100644 --- a/pkg/services/alerting/notifiers/teams_test.go +++ b/pkg/services/alerting/notifiers/teams_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestTeamsNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "teams", Settings: settingsJSON, @@ -33,7 +33,7 @@ func TestTeamsNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "teams", Settings: settingsJSON, @@ -55,7 +55,7 @@ func TestTeamsNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "teams", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/telegram.go b/pkg/services/alerting/notifiers/telegram.go index a5876b77b228..741c0fe732c5 100644 --- a/pkg/services/alerting/notifiers/telegram.go +++ b/pkg/services/alerting/notifiers/telegram.go @@ -9,7 +9,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -60,7 +60,7 @@ type TelegramNotifier struct { log log.Logger } -func NewTelegramNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewTelegramNotifier(model *models.AlertNotification) (alerting.Notifier, error) { if model.Settings == nil { return nil, alerting.ValidationError{Reason: "No Settings Supplied"} } @@ -86,7 +86,7 @@ func NewTelegramNotifier(model *m.AlertNotification) (alerting.Notifier, error) }, nil } -func (this *TelegramNotifier) buildMessage(evalContext *alerting.EvalContext, sendImageInline bool) *m.SendWebhookSync { +func (this *TelegramNotifier) buildMessage(evalContext *alerting.EvalContext, sendImageInline bool) *models.SendWebhookSync { if sendImageInline { cmd, err := this.buildMessageInlineImage(evalContext) if err == nil { @@ -98,7 +98,7 @@ func (this *TelegramNotifier) buildMessage(evalContext *alerting.EvalContext, se return this.buildMessageLinkedImage(evalContext) } -func (this *TelegramNotifier) buildMessageLinkedImage(evalContext *alerting.EvalContext) *m.SendWebhookSync { +func (this *TelegramNotifier) buildMessageLinkedImage(evalContext *alerting.EvalContext) *models.SendWebhookSync { message := fmt.Sprintf("%s\nState: %s\nMessage: %s\n", evalContext.GetNotificationTitle(), evalContext.Rule.Name, evalContext.Rule.Message) ruleUrl, err := evalContext.GetRuleUrl() @@ -122,7 +122,7 @@ func (this *TelegramNotifier) buildMessageLinkedImage(evalContext *alerting.Eval return cmd } -func (this *TelegramNotifier) buildMessageInlineImage(evalContext *alerting.EvalContext) (*m.SendWebhookSync, error) { +func (this *TelegramNotifier) buildMessageInlineImage(evalContext *alerting.EvalContext) (*models.SendWebhookSync, error) { var imageFile *os.File var err error @@ -153,7 +153,7 @@ func (this *TelegramNotifier) buildMessageInlineImage(evalContext *alerting.Eval return cmd, nil } -func (this *TelegramNotifier) generateTelegramCmd(message string, messageField string, apiAction string, extraConf func(writer *multipart.Writer)) *m.SendWebhookSync { +func (this *TelegramNotifier) generateTelegramCmd(message string, messageField string, apiAction string, extraConf func(writer *multipart.Writer)) *models.SendWebhookSync { var body bytes.Buffer w := multipart.NewWriter(&body) @@ -170,7 +170,7 @@ func (this *TelegramNotifier) generateTelegramCmd(message string, messageField s this.log.Info("Sending telegram notification", "chat_id", this.ChatID, "bot_token", this.BotToken, "apiAction", apiAction) url := fmt.Sprintf(telegramApiUrl, this.BotToken, apiAction) - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: url, Body: body.String(), HttpMethod: "POST", @@ -227,7 +227,7 @@ func appendIfPossible(message string, extra string, sizeLimit int) string { } func (this *TelegramNotifier) Notify(evalContext *alerting.EvalContext) error { - var cmd *m.SendWebhookSync + var cmd *models.SendWebhookSync if evalContext.ImagePublicUrl == "" && this.UploadImage { cmd = this.buildMessage(evalContext, true) } else { diff --git a/pkg/services/alerting/notifiers/telegram_test.go b/pkg/services/alerting/notifiers/telegram_test.go index 9906a2ffd957..3559555439e5 100644 --- a/pkg/services/alerting/notifiers/telegram_test.go +++ b/pkg/services/alerting/notifiers/telegram_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" . "github.com/smartystreets/goconvey/convey" ) @@ -18,7 +18,7 @@ func TestTelegramNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "telegram_testing", Type: "telegram", Settings: settingsJSON, @@ -36,7 +36,7 @@ func TestTelegramNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "telegram_testing", Type: "telegram", Settings: settingsJSON, @@ -57,7 +57,7 @@ func TestTelegramNotifier(t *testing.T) { &alerting.Rule{ Name: "This is an alarm", Message: "Some kind of message.", - State: m.AlertStateOK, + State: models.AlertStateOK, }) caption := generateImageCaption(evalContext, "http://grafa.url/abcdef", "") @@ -74,7 +74,7 @@ func TestTelegramNotifier(t *testing.T) { &alerting.Rule{ Name: "This is an alarm", Message: "Some kind of message.", - State: m.AlertStateOK, + State: models.AlertStateOK, }) caption := generateImageCaption(evalContext, @@ -92,7 +92,7 @@ func TestTelegramNotifier(t *testing.T) { &alerting.Rule{ Name: "This is an alarm", Message: "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis scelerisque. Nulla ipsum ex, iaculis vitae vehicula sit amet, fermentum eu eros.", - State: m.AlertStateOK, + State: models.AlertStateOK, }) caption := generateImageCaption(evalContext, @@ -109,7 +109,7 @@ func TestTelegramNotifier(t *testing.T) { &alerting.Rule{ Name: "This is an alarm", Message: "Some kind of message that is too long for appending to our pretty little message, this line is actually exactly 197 chars long and I will get there in the end I promise I will. Yes siree that's it. But suddenly Telegram increased the length so now we need some lorem ipsum to fix this test. Here we go: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus consectetur molestie cursus. Donec suscipit egestas nisi. Proin ut efficitur ex. Mauris mi augue, volutpat a nisi vel, euismod dictum arcu. Sed quis tempor eros, sed malesuada dolor. Ut orci augue, viverra sit amet blandit quis, faucibus sit amet ex. Duis condimentum efficitur lectus, id dignissim quam tempor id. Morbi sollicitudin rhoncus diam, id tincidunt lectus scelerisque vitae. Etiam imperdiet semper sem, vel eleifend ligula mollis eget. Etiam ultrices fringilla lacus, sit amet pharetra ex blandit quis. Suspendisse in egestas neque, et posuere lectus. Vestibulum eu ex dui. Sed molestie nulla a lobortis sceleri", - State: m.AlertStateOK, + State: models.AlertStateOK, }) caption := generateImageCaption(evalContext, diff --git a/pkg/services/alerting/notifiers/threema.go b/pkg/services/alerting/notifiers/threema.go index 2360073d2281..6e4aa7bc946e 100644 --- a/pkg/services/alerting/notifiers/threema.go +++ b/pkg/services/alerting/notifiers/threema.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -76,7 +76,7 @@ type ThreemaNotifier struct { log log.Logger } -func NewThreemaNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewThreemaNotifier(model *models.AlertNotification) (alerting.Notifier, error) { if model.Settings == nil { return nil, alerting.ValidationError{Reason: "No Settings Supplied"} } @@ -127,11 +127,11 @@ func (notifier *ThreemaNotifier) Notify(evalContext *alerting.EvalContext) error // Determine emoji stateEmoji := "" switch evalContext.Rule.State { - case m.AlertStateOK: + case models.AlertStateOK: stateEmoji = "\u2705 " // White Heavy Check Mark - case m.AlertStateNoData: + case models.AlertStateNoData: stateEmoji = "\u2753 " // Black Question Mark Ornament - case m.AlertStateAlerting: + case models.AlertStateAlerting: stateEmoji = "\u26A0 " // Warning sign } @@ -154,7 +154,7 @@ func (notifier *ThreemaNotifier) Notify(evalContext *alerting.EvalContext) error headers := map[string]string{ "Content-Type": "application/x-www-form-urlencoded", } - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: url, Body: body, HttpMethod: "POST", diff --git a/pkg/services/alerting/notifiers/threema_test.go b/pkg/services/alerting/notifiers/threema_test.go index 3f23730a249a..2c50b7d2058c 100644 --- a/pkg/services/alerting/notifiers/threema_test.go +++ b/pkg/services/alerting/notifiers/threema_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" . "github.com/smartystreets/goconvey/convey" ) @@ -17,7 +17,7 @@ func TestThreemaNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "threema_testing", Type: "threema", Settings: settingsJSON, @@ -36,7 +36,7 @@ func TestThreemaNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "threema_testing", Type: "threema", Settings: settingsJSON, @@ -63,7 +63,7 @@ func TestThreemaNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "threema_testing", Type: "threema", Settings: settingsJSON, @@ -83,7 +83,7 @@ func TestThreemaNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "threema_testing", Type: "threema", Settings: settingsJSON, @@ -103,7 +103,7 @@ func TestThreemaNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "threema_testing", Type: "threema", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/victorops_test.go b/pkg/services/alerting/notifiers/victorops_test.go index 6ac806a82cc5..258d2900a22b 100644 --- a/pkg/services/alerting/notifiers/victorops_test.go +++ b/pkg/services/alerting/notifiers/victorops_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestVictoropsNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "victorops_testing", Type: "victorops", Settings: settingsJSON, @@ -33,7 +33,7 @@ func TestVictoropsNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "victorops_testing", Type: "victorops", Settings: settingsJSON, diff --git a/pkg/services/alerting/notifiers/webhook.go b/pkg/services/alerting/notifiers/webhook.go index 7c582a41aeb8..31b5f7a82080 100644 --- a/pkg/services/alerting/notifiers/webhook.go +++ b/pkg/services/alerting/notifiers/webhook.go @@ -4,7 +4,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/alerting" ) @@ -40,7 +40,7 @@ func init() { } -func NewWebHookNotifier(model *m.AlertNotification) (alerting.Notifier, error) { +func NewWebHookNotifier(model *models.AlertNotification) (alerting.Notifier, error) { url := model.Settings.Get("url").MustString() if url == "" { return nil, alerting.ValidationError{Reason: "Could not find url property in settings"} @@ -90,7 +90,7 @@ func (this *WebhookNotifier) Notify(evalContext *alerting.EvalContext) error { body, _ := bodyJSON.MarshalJSON() - cmd := &m.SendWebhookSync{ + cmd := &models.SendWebhookSync{ Url: this.Url, User: this.User, Password: this.Password, diff --git a/pkg/services/alerting/notifiers/webhook_test.go b/pkg/services/alerting/notifiers/webhook_test.go index b2d944eb6e94..af48f1f1aa6d 100644 --- a/pkg/services/alerting/notifiers/webhook_test.go +++ b/pkg/services/alerting/notifiers/webhook_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" . "github.com/smartystreets/goconvey/convey" ) @@ -16,7 +16,7 @@ func TestWebhookNotifier(t *testing.T) { json := `{ }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "webhook", Settings: settingsJSON, @@ -33,7 +33,7 @@ func TestWebhookNotifier(t *testing.T) { }` settingsJSON, _ := simplejson.NewJson([]byte(json)) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: "ops", Type: "webhook", Settings: settingsJSON, diff --git a/pkg/services/alerting/reader.go b/pkg/services/alerting/reader.go index 3f033a746f27..0df826e9ea5d 100644 --- a/pkg/services/alerting/reader.go +++ b/pkg/services/alerting/reader.go @@ -7,7 +7,7 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) type RuleReader interface { @@ -16,7 +16,6 @@ type RuleReader interface { type DefaultRuleReader struct { sync.RWMutex - //serverID string serverPosition int clusterSize int log log.Logger @@ -40,7 +39,7 @@ func (arr *DefaultRuleReader) initReader() { } func (arr *DefaultRuleReader) Fetch() []*Rule { - cmd := &m.GetAllAlertsQuery{} + cmd := &models.GetAllAlertsQuery{} if err := bus.Dispatch(cmd); err != nil { arr.log.Error("Could not load alerts", "error", err) diff --git a/pkg/services/alerting/result_handler.go b/pkg/services/alerting/result_handler.go index 6f2669ff41a9..d82421d7506d 100644 --- a/pkg/services/alerting/result_handler.go +++ b/pkg/services/alerting/result_handler.go @@ -7,7 +7,8 @@ import ( "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" "github.com/grafana/grafana/pkg/infra/metrics" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/services/annotations" "github.com/grafana/grafana/pkg/services/rendering" ) @@ -47,7 +48,7 @@ func (handler *DefaultResultHandler) Handle(evalContext *EvalContext) error { if evalContext.ShouldUpdateAlertState() { handler.log.Info("New state change", "alertId", evalContext.Rule.Id, "newState", evalContext.Rule.State, "prev state", evalContext.PrevAlertState) - cmd := &m.SetAlertStateCommand{ + cmd := &models.SetAlertStateCommand{ AlertId: evalContext.Rule.Id, OrgId: evalContext.Rule.OrgId, State: evalContext.Rule.State, @@ -56,12 +57,12 @@ func (handler *DefaultResultHandler) Handle(evalContext *EvalContext) error { } if err := bus.Dispatch(cmd); err != nil { - if err == m.ErrCannotChangeStateOnPausedAlert { + if err == models.ErrCannotChangeStateOnPausedAlert { handler.log.Error("Cannot change state on alert that's paused", "error", err) return err } - if err == m.ErrRequiresNewState { + if err == models.ErrRequiresNewState { handler.log.Info("Alert already updated") return nil } diff --git a/pkg/services/alerting/rule.go b/pkg/services/alerting/rule.go index f62690a2d960..b5b6f4660e64 100644 --- a/pkg/services/alerting/rule.go +++ b/pkg/services/alerting/rule.go @@ -8,7 +8,7 @@ import ( "time" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) var ( @@ -26,9 +26,9 @@ type Rule struct { Message string LastStateChange time.Time For time.Duration - NoDataState m.NoDataOption - ExecutionErrorState m.ExecutionErrorOption - State m.AlertStateType + NoDataState models.NoDataOption + ExecutionErrorState models.ExecutionErrorOption + State models.AlertStateType Conditions []Condition Notifications []string @@ -103,7 +103,7 @@ func getTimeDurationStringToSeconds(str string) (int64, error) { return int64(value * multiplier), nil } -func NewRuleFromDBAlert(ruleDef *m.Alert) (*Rule, error) { +func NewRuleFromDBAlert(ruleDef *models.Alert) (*Rule, error) { model := &Rule{} model.Id = ruleDef.Id model.OrgId = ruleDef.OrgId @@ -114,8 +114,8 @@ func NewRuleFromDBAlert(ruleDef *m.Alert) (*Rule, error) { model.State = ruleDef.State model.LastStateChange = ruleDef.NewStateDate model.For = ruleDef.For - model.NoDataState = m.NoDataOption(ruleDef.Settings.Get("noDataState").MustString("no_data")) - model.ExecutionErrorState = m.ExecutionErrorOption(ruleDef.Settings.Get("executionErrorState").MustString("alerting")) + model.NoDataState = models.NoDataOption(ruleDef.Settings.Get("noDataState").MustString("no_data")) + model.ExecutionErrorState = models.ExecutionErrorOption(ruleDef.Settings.Get("executionErrorState").MustString("alerting")) model.StateChanges = ruleDef.StateChanges model.Frequency = ruleDef.Frequency diff --git a/pkg/services/alerting/rule_test.go b/pkg/services/alerting/rule_test.go index ca533c36210f..853fb5d17b5c 100644 --- a/pkg/services/alerting/rule_test.go +++ b/pkg/services/alerting/rule_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/services/sqlstore" . "github.com/smartystreets/goconvey/convey" ) @@ -60,10 +60,10 @@ func TestAlertRuleModel(t *testing.T) { }) Convey("can construct alert rule model", func() { - firstNotification := m.CreateAlertNotificationCommand{OrgId: 1, Name: "1"} + firstNotification := models.CreateAlertNotificationCommand{OrgId: 1, Name: "1"} err := sqlstore.CreateAlertNotificationCommand(&firstNotification) So(err, ShouldBeNil) - secondNotification := m.CreateAlertNotificationCommand{Uid: "notifier2", OrgId: 1, Name: "2"} + secondNotification := models.CreateAlertNotificationCommand{Uid: "notifier2", OrgId: 1, Name: "2"} err = sqlstore.CreateAlertNotificationCommand(&secondNotification) So(err, ShouldBeNil) @@ -92,7 +92,7 @@ func TestAlertRuleModel(t *testing.T) { alertJSON, jsonErr := simplejson.NewJson([]byte(json)) So(jsonErr, ShouldBeNil) - alert := &m.Alert{ + alert := &models.Alert{ Id: 1, OrgId: 1, DashboardId: 1, @@ -129,7 +129,7 @@ func TestAlertRuleModel(t *testing.T) { alertJSON, jsonErr := simplejson.NewJson([]byte(json)) So(jsonErr, ShouldBeNil) - alert := &m.Alert{ + alert := &models.Alert{ Id: 1, OrgId: 1, DashboardId: 1, @@ -167,7 +167,7 @@ func TestAlertRuleModel(t *testing.T) { alertJSON, jsonErr := simplejson.NewJson([]byte(json)) So(jsonErr, ShouldBeNil) - alert := &m.Alert{ + alert := &models.Alert{ Id: 1, OrgId: 1, DashboardId: 1, diff --git a/pkg/services/alerting/test_notification.go b/pkg/services/alerting/test_notification.go index fbb1633d4a5b..5cb18d2b42ee 100644 --- a/pkg/services/alerting/test_notification.go +++ b/pkg/services/alerting/test_notification.go @@ -8,11 +8,11 @@ import ( "github.com/grafana/grafana/pkg/components/null" "github.com/grafana/grafana/pkg/components/simplejson" "github.com/grafana/grafana/pkg/infra/log" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) type NotificationTestCommand struct { - State m.AlertStateType + State models.AlertStateType Name string Type string Settings *simplejson.Json @@ -29,7 +29,7 @@ func init() { func handleNotificationTestCommand(cmd *NotificationTestCommand) error { notifier := NewNotificationService(nil).(*notificationService) - model := &m.AlertNotification{ + model := &models.AlertNotification{ Name: cmd.Name, Type: cmd.Type, Settings: cmd.Settings, @@ -51,7 +51,7 @@ func createTestEvalContext(cmd *NotificationTestCommand) *EvalContext { PanelId: 1, Name: "Test notification", Message: "Someone is testing the alert notification within grafana.", - State: m.AlertStateAlerting, + State: models.AlertStateAlerting, } ctx := NewEvalContext(context.Background(), testRule) diff --git a/pkg/services/alerting/test_rule.go b/pkg/services/alerting/test_rule.go index 360ee065de0f..736dd287dbec 100644 --- a/pkg/services/alerting/test_rule.go +++ b/pkg/services/alerting/test_rule.go @@ -6,14 +6,14 @@ import ( "github.com/grafana/grafana/pkg/bus" "github.com/grafana/grafana/pkg/components/simplejson" - m "github.com/grafana/grafana/pkg/models" + "github.com/grafana/grafana/pkg/models" ) type AlertTestCommand struct { Dashboard *simplejson.Json PanelId int64 OrgId int64 - User *m.SignedInUser + User *models.SignedInUser Result *EvalContext } @@ -24,7 +24,7 @@ func init() { func handleAlertTestCommand(cmd *AlertTestCommand) error { - dash := m.NewDashboardFromJson(cmd.Dashboard) + dash := models.NewDashboardFromJson(cmd.Dashboard) extractor := NewDashAlertExtractor(dash, cmd.OrgId, cmd.User) alerts, err := extractor.GetAlerts() From 34f9b3ff2b4a14121a4f2429d3c6d70e0e2026ac Mon Sep 17 00:00:00 2001 From: Dominik Prokop Date: Tue, 14 May 2019 08:46:35 +0200 Subject: [PATCH 020/166] Explore: use @grafana/ui legend (#17027) --- .../src/components/Graph/GraphLegend.tsx | 8 +- .../src/components/Graph/GraphLegendItem.tsx | 35 +- .../src/components/Legend/LegendList.tsx | 2 +- .../components/Legend/LegendSeriesIcon.tsx | 32 +- .../src/components/Legend/SeriesIcon.tsx | 9 +- packages/grafana-ui/src/components/index.ts | 12 +- public/app/features/explore/Graph.tsx | 108 +- public/app/features/explore/Legend.tsx | 66 - .../explore/__snapshots__/Graph.test.tsx.snap | 1150 ++++------------- 9 files changed, 390 insertions(+), 1032 deletions(-) delete mode 100644 public/app/features/explore/Legend.tsx diff --git a/packages/grafana-ui/src/components/Graph/GraphLegend.tsx b/packages/grafana-ui/src/components/Graph/GraphLegend.tsx index 451acf4bac80..5b7a0251e052 100644 --- a/packages/grafana-ui/src/components/Graph/GraphLegend.tsx +++ b/packages/grafana-ui/src/components/Graph/GraphLegend.tsx @@ -14,10 +14,10 @@ interface GraphLegendProps extends LegendProps { displayMode: LegendDisplayMode; sortBy?: string; sortDesc?: boolean; - onSeriesColorChange: SeriesColorChangeHandler; + onSeriesColorChange?: SeriesColorChangeHandler; onSeriesAxisToggle?: SeriesAxisToggleHandler; - onToggleSort: (sortBy: string) => void; - onLabelClick: (item: LegendItem, event: React.MouseEvent) => void; + onToggleSort?: (sortBy: string) => void; + onLabelClick?: (item: LegendItem, event: React.MouseEvent) => void; } export const GraphLegend: React.FunctionComponent = ({ @@ -116,3 +116,5 @@ export const GraphLegend: React.FunctionComponent = ({ /> ); }; + +GraphLegend.displayName = 'GraphLegend'; diff --git a/packages/grafana-ui/src/components/Graph/GraphLegendItem.tsx b/packages/grafana-ui/src/components/Graph/GraphLegendItem.tsx index e116287d4d21..37371fe06644 100644 --- a/packages/grafana-ui/src/components/Graph/GraphLegendItem.tsx +++ b/packages/grafana-ui/src/components/Graph/GraphLegendItem.tsx @@ -10,9 +10,9 @@ export interface GraphLegendItemProps { key?: React.Key; item: LegendItem; className?: string; - onLabelClick: (item: LegendItem, event: React.MouseEvent) => void; - onSeriesColorChange: SeriesColorChangeHandler; - onToggleAxis: () => void; + onLabelClick?: (item: LegendItem, event: React.MouseEvent) => void; + onSeriesColorChange?: SeriesColorChangeHandler; + onToggleAxis?: () => void; } export const GraphLegendListItem: React.FunctionComponent = ({ @@ -21,19 +21,31 @@ export const GraphLegendListItem: React.FunctionComponent onToggleAxis, onLabelClick, }) => { + const theme = useContext(ThemeContext); + return ( <> onSeriesColorChange(item.label, color)} + onColorChange={color => { + if (onSeriesColorChange) { + onSeriesColorChange(item.label, color); + } + }} onToggleAxis={onToggleAxis} yAxis={item.yAxis} />
    onLabelClick(item, event)} + onClick={event => { + if (onLabelClick) { + onLabelClick(item, event); + } + }} className={css` cursor: pointer; white-space: nowrap; + color: ${!item.isVisible && theme.colors.linkDisabled}; `} > {item.label} @@ -74,13 +86,22 @@ export const GraphLegendTableRow: React.FunctionComponent `} > onSeriesColorChange(item.label, color)} + onColorChange={color => { + if (onSeriesColorChange) { + onSeriesColorChange(item.label, color); + } + }} onToggleAxis={onToggleAxis} yAxis={item.yAxis} />
    onLabelClick(item, event)} + onClick={event => { + if (onLabelClick) { + onLabelClick(item, event); + } + }} className={css` cursor: pointer; white-space: nowrap; diff --git a/packages/grafana-ui/src/components/Legend/LegendList.tsx b/packages/grafana-ui/src/components/Legend/LegendList.tsx index d103aa3ed806..f220b10a5876 100644 --- a/packages/grafana-ui/src/components/Legend/LegendList.tsx +++ b/packages/grafana-ui/src/components/Legend/LegendList.tsx @@ -28,7 +28,7 @@ export const LegendList: React.FunctionComponent = ({ ); }; - const getItemKey = (item: LegendItem) => item.label; + const getItemKey = (item: LegendItem) => `${item.label}`; const styles = { wrapper: cx( diff --git a/packages/grafana-ui/src/components/Legend/LegendSeriesIcon.tsx b/packages/grafana-ui/src/components/Legend/LegendSeriesIcon.tsx index 1913c2e500d2..787b818c0030 100644 --- a/packages/grafana-ui/src/components/Legend/LegendSeriesIcon.tsx +++ b/packages/grafana-ui/src/components/Legend/LegendSeriesIcon.tsx @@ -1,8 +1,10 @@ import React from 'react'; +import { css, cx } from 'emotion'; import { SeriesColorPicker } from '../ColorPicker/ColorPicker'; -import { SeriesIcon } from './SeriesIcon'; +import { SeriesIcon, SeriesIconProps } from './SeriesIcon'; interface LegendSeriesIconProps { + disabled: boolean; color: string; yAxis: number; onColorChange: (color: string) => void; @@ -10,12 +12,36 @@ interface LegendSeriesIconProps { } export const LegendSeriesIcon: React.FunctionComponent = ({ + disabled, yAxis, color, onColorChange, onToggleAxis, }) => { - return ( + let iconProps: SeriesIconProps = { + color, + }; + + if (!disabled) { + iconProps = { + ...iconProps, + className: 'pointer', + }; + } + + return disabled ? ( + + + + ) : ( = > {({ ref, showColorPicker, hideColorPicker }) => ( - + )} diff --git a/packages/grafana-ui/src/components/Legend/SeriesIcon.tsx b/packages/grafana-ui/src/components/Legend/SeriesIcon.tsx index 091d79f7fd0d..70709a0fcd5c 100644 --- a/packages/grafana-ui/src/components/Legend/SeriesIcon.tsx +++ b/packages/grafana-ui/src/components/Legend/SeriesIcon.tsx @@ -1,5 +1,10 @@ import React from 'react'; +import { cx } from 'emotion'; -export const SeriesIcon: React.FunctionComponent<{ color: string }> = ({ color }) => { - return ; +export interface SeriesIconProps { + color: string; + className?: string; +} +export const SeriesIcon: React.FunctionComponent = ({ color, className }) => { + return ; }; diff --git a/packages/grafana-ui/src/components/index.ts b/packages/grafana-ui/src/components/index.ts index 5a4f58626c6a..860dd5a97ab0 100644 --- a/packages/grafana-ui/src/components/index.ts +++ b/packages/grafana-ui/src/components/index.ts @@ -45,10 +45,20 @@ export { TableInputCSV } from './Table/TableInputCSV'; export { BigValue } from './BigValue/BigValue'; export { Gauge } from './Gauge/Gauge'; export { Graph } from './Graph/Graph'; +export { GraphLegend } from './Graph/GraphLegend'; export { GraphWithLegend } from './Graph/GraphWithLegend'; export { BarGauge } from './BarGauge/BarGauge'; export { VizRepeater } from './VizRepeater/VizRepeater'; -export { LegendOptions, LegendBasicOptions, LegendRenderOptions, LegendList, LegendTable } from './Legend/Legend'; +export { + LegendOptions, + LegendBasicOptions, + LegendRenderOptions, + LegendList, + LegendTable, + LegendItem, + LegendPlacement, + LegendDisplayMode, +} from './Legend/Legend'; // Panel editors export { ThresholdsEditor } from './ThresholdsEditor/ThresholdsEditor'; export { ClickOutsideWrapper } from './ClickOutsideWrapper/ClickOutsideWrapper'; diff --git a/public/app/features/explore/Graph.tsx b/public/app/features/explore/Graph.tsx index f9c48fc92c72..b5cdca318afa 100644 --- a/public/app/features/explore/Graph.tsx +++ b/public/app/features/explore/Graph.tsx @@ -1,17 +1,15 @@ import $ from 'jquery'; import React, { PureComponent } from 'react'; +import difference from 'lodash/difference'; import 'vendor/flot/jquery.flot'; import 'vendor/flot/jquery.flot.time'; import 'vendor/flot/jquery.flot.selection'; import 'vendor/flot/jquery.flot.stack'; -import { TimeZone, AbsoluteTimeRange } from '@grafana/ui'; +import { TimeZone, AbsoluteTimeRange, GraphLegend, LegendItem, LegendDisplayMode } from '@grafana/ui'; import TimeSeries from 'app/core/time_series2'; -import Legend from './Legend'; -import { equal, intersect } from './utils/set'; - const MAX_NUMBER_OF_TIME_SERIES = 20; // Copied from graph.ts @@ -89,7 +87,7 @@ interface GraphState { * Type parameter refers to the `alias` property of a `TimeSeries`. * Consequently, all series sharing the same alias will share visibility state. */ - hiddenSeries: Set; + hiddenSeries: string[]; showAllTimeSeries: boolean; } @@ -98,11 +96,11 @@ export class Graph extends PureComponent { dynamicOptions = null; state = { - hiddenSeries: new Set(), + hiddenSeries: [], showAllTimeSeries: false, }; - getGraphData() { + getGraphData(): TimeSeries[] { const { data } = this.props; return this.state.showAllTimeSeries ? data : data.slice(0, MAX_NUMBER_OF_TIME_SERIES); @@ -121,7 +119,7 @@ export class Graph extends PureComponent { prevProps.split !== this.props.split || prevProps.height !== this.props.height || prevProps.width !== this.props.width || - !equal(prevState.hiddenSeries, this.state.hiddenSeries) + prevState.hiddenSeries !== this.state.hiddenSeries ) { this.draw(); } @@ -168,38 +166,6 @@ export class Graph extends PureComponent { ); }; - onToggleSeries = (series: TimeSeries, exclusive: boolean) => { - this.setState((state, props) => { - const { data, onToggleSeries } = props; - const { hiddenSeries } = state; - - // Deduplicate series as visibility tracks the alias property - const oneSeriesVisible = hiddenSeries.size === new Set(data.map(d => d.alias)).size - 1; - - let nextHiddenSeries = new Set(); - if (exclusive) { - if (hiddenSeries.has(series.alias) || !oneSeriesVisible) { - nextHiddenSeries = new Set(data.filter(d => d.alias !== series.alias).map(d => d.alias)); - } - } else { - // Prune hidden series no longer part of those available from the most recent query - const availableSeries = new Set(data.map(d => d.alias)); - nextHiddenSeries = intersect(new Set(hiddenSeries), availableSeries); - if (nextHiddenSeries.has(series.alias)) { - nextHiddenSeries.delete(series.alias); - } else { - nextHiddenSeries.add(series.alias); - } - } - if (onToggleSeries) { - onToggleSeries(series.alias, nextHiddenSeries); - } - return { - hiddenSeries: nextHiddenSeries, - }; - }, this.draw); - }; - draw() { const { userOptions = {} } = this.props; const { hiddenSeries } = this.state; @@ -210,7 +176,7 @@ export class Graph extends PureComponent { if (data && data.length > 0) { series = data - .filter((ts: TimeSeries) => !hiddenSeries.has(ts.alias)) + .filter((ts: TimeSeries) => hiddenSeries.indexOf(ts.alias) === -1) .map((ts: TimeSeries) => ({ color: ts.color, label: ts.label, @@ -229,11 +195,57 @@ export class Graph extends PureComponent { $.plot($el, series, options); } - render() { - const { height = 100, id = 'graph' } = this.props; + getLegendItems = (): LegendItem[] => { const { hiddenSeries } = this.state; const data = this.getGraphData(); + return data.map(series => { + return { + label: series.alias, + color: series.color, + isVisible: hiddenSeries.indexOf(series.alias) === -1, + yAxis: 1, + }; + }); + }; + + onSeriesToggle(label: string, event: React.MouseEvent) { + // This implementation is more or less a copy of GraphPanel's logic. + // TODO: we need to use Graph's panel controller or split it into smaller + // controllers to remove code duplication. Right now we cant easily use that, since Explore + // is not using SeriesData for graph yet + + const exclusive = event.ctrlKey || event.metaKey || event.shiftKey; + + this.setState((state, props) => { + const { data } = props; + let nextHiddenSeries = []; + if (exclusive) { + // Toggling series with key makes the series itself to toggle + if (state.hiddenSeries.indexOf(label) > -1) { + nextHiddenSeries = state.hiddenSeries.filter(series => series !== label); + } else { + nextHiddenSeries = state.hiddenSeries.concat([label]); + } + } else { + // Toggling series with out key toggles all the series but the clicked one + const allSeriesLabels = data.map(series => series.label); + + if (state.hiddenSeries.length + 1 === allSeriesLabels.length) { + nextHiddenSeries = []; + } else { + nextHiddenSeries = difference(allSeriesLabels, [label]); + } + } + + return { + hiddenSeries: nextHiddenSeries, + }; + }); + } + + render() { + const { height = 100, id = 'graph' } = this.props; return ( <> {this.props.data && this.props.data.length > MAX_NUMBER_OF_TIME_SERIES && !this.state.showAllTimeSeries && ( @@ -246,7 +258,15 @@ export class Graph extends PureComponent {
    )}
    - + + { + this.onSeriesToggle(item.label, event); + }} + /> ); } diff --git a/public/app/features/explore/Legend.tsx b/public/app/features/explore/Legend.tsx deleted file mode 100644 index 3b67aa74d917..000000000000 --- a/public/app/features/explore/Legend.tsx +++ /dev/null @@ -1,66 +0,0 @@ -import React, { MouseEvent, PureComponent } from 'react'; -import classNames from 'classnames'; -import { TimeSeries } from 'app/core/core'; - -interface LegendProps { - data: TimeSeries[]; - hiddenSeries: Set; - onToggleSeries?: (series: TimeSeries, exclusive: boolean) => void; -} - -interface LegendItemProps { - hidden: boolean; - onClickLabel?: (series: TimeSeries, event: MouseEvent) => void; - series: TimeSeries; -} - -class LegendItem extends PureComponent { - onClickLabel = e => this.props.onClickLabel(this.props.series, e); - - render() { - const { hidden, series } = this.props; - const seriesClasses = classNames({ - 'graph-legend-series-hidden': hidden, - }); - return ( - - ); - } -} - -export default class Legend extends PureComponent { - static defaultProps = { - onToggleSeries: () => {}, - }; - - onClickLabel = (series: TimeSeries, event: MouseEvent) => { - const { onToggleSeries } = this.props; - const exclusive = event.ctrlKey || event.metaKey || event.shiftKey; - onToggleSeries(series, !exclusive); - }; - - render() { - const { data, hiddenSeries } = this.props; - const items = data || []; - return ( -
    - {items.map((series, i) => ( -
    - ); - } -} diff --git a/public/app/features/explore/__snapshots__/Graph.test.tsx.snap b/public/app/features/explore/__snapshots__/Graph.test.tsx.snap index c38fb26a2523..d43f94856055 100644 --- a/public/app/features/explore/__snapshots__/Graph.test.tsx.snap +++ b/public/app/features/explore/__snapshots__/Graph.test.tsx.snap @@ -11,450 +11,128 @@ exports[`Render should render component 1`] = ` } } /> - `; @@ -484,473 +162,134 @@ exports[`Render should render component with disclaimer 1`] = ` } } /> - `; @@ -966,10 +305,11 @@ exports[`Render should show query return no time series 1`] = ` } } /> - `; From 79ac3fd699476328e538d4d1f73708fc0fc66715 Mon Sep 17 00:00:00 2001 From: Oleg Gaidarenko Date: Tue, 14 May 2019 10:18:28 +0300 Subject: [PATCH 021/166] Chore: remove use of `== false` (#17036) Interestingly enough, golint or revive doesn't not prohibit the use that construction :) Ref #17035 --- pkg/middleware/auth_proxy.go | 6 +++--- pkg/middleware/auth_proxy/auth_proxy.go | 2 +- pkg/services/ldap/settings.go | 7 ++++--- 3 files changed, 8 insertions(+), 7 deletions(-) diff --git a/pkg/middleware/auth_proxy.go b/pkg/middleware/auth_proxy.go index 6dc69dda8b5f..d3d8d8e77d8a 100644 --- a/pkg/middleware/auth_proxy.go +++ b/pkg/middleware/auth_proxy.go @@ -20,17 +20,17 @@ func initContextWithAuthProxy(store *remotecache.RemoteCache, ctx *m.ReqContext, }) // Bail if auth proxy is not enabled - if auth.IsEnabled() == false { + if !auth.IsEnabled() { return false } // If the there is no header - we can't move forward - if auth.HasHeader() == false { + if !auth.HasHeader() { return false } // Check if allowed to continue with this IP - if result, err := auth.IsAllowedIP(); result == false { + if result, err := auth.IsAllowedIP(); !result { ctx.Handle(407, err.Error(), err.DetailsError) return true } diff --git a/pkg/middleware/auth_proxy/auth_proxy.go b/pkg/middleware/auth_proxy/auth_proxy.go index b9e71d1b480d..98bacbeccf47 100644 --- a/pkg/middleware/auth_proxy/auth_proxy.go +++ b/pkg/middleware/auth_proxy/auth_proxy.go @@ -92,7 +92,7 @@ func New(options *Options) *AuthProxy { func (auth *AuthProxy) IsEnabled() bool { // Bail if the setting is not enabled - if auth.enabled == false { + if !auth.enabled { return false } diff --git a/pkg/services/ldap/settings.go b/pkg/services/ldap/settings.go index de2da2402bfe..0a0f66d9d734 100644 --- a/pkg/services/ldap/settings.go +++ b/pkg/services/ldap/settings.go @@ -5,12 +5,12 @@ import ( "sync" "github.com/BurntSushi/toml" - "github.com/grafana/grafana/pkg/util/errutil" "golang.org/x/xerrors" "github.com/grafana/grafana/pkg/infra/log" m "github.com/grafana/grafana/pkg/models" "github.com/grafana/grafana/pkg/setting" + "github.com/grafana/grafana/pkg/util/errutil" ) type Config struct { @@ -68,9 +68,10 @@ func IsEnabled() bool { // ReloadConfig reads the config from the disc and caches it. func ReloadConfig() error { - if IsEnabled() == false { + if !IsEnabled() { return nil } + loadingMutex.Lock() defer loadingMutex.Unlock() @@ -82,7 +83,7 @@ func ReloadConfig() error { // GetConfig returns the LDAP config if LDAP is enabled otherwise it returns nil. It returns either cached value of // the config or it reads it and caches it first. func GetConfig() (*Config, error) { - if IsEnabled() == false { + if !IsEnabled() { return nil, nil } From 51c99fc68d5830a27b5509665dc2b42b88ab00b3 Mon Sep 17 00:00:00 2001 From: Carl Bergquist Date: Tue, 14 May 2019 10:30:05 +0200 Subject: [PATCH 022/166] Docs: adds note about removing session storage (#17003) closes #17000 --- docs/sources/installation/upgrading.md | 6 ++++++ docs/sources/tutorials/ha_setup.md | 3 ++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/docs/sources/installation/upgrading.md b/docs/sources/installation/upgrading.md index bd2a5434b25f..22195cb9df50 100644 --- a/docs/sources/installation/upgrading.md +++ b/docs/sources/installation/upgrading.md @@ -169,3 +169,9 @@ configuration. If you're embedding Grafana in a ``, `