AlertTabCtrl.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import _ from 'lodash';
  2. import coreModule from 'app/core/core_module';
  3. import { ThresholdMapper } from './state/ThresholdMapper';
  4. import { QueryPart } from 'app/core/components/query_part/query_part';
  5. import alertDef from './state/alertDef';
  6. import config from 'app/core/config';
  7. import appEvents from 'app/core/app_events';
  8. import { BackendSrv } from 'app/core/services/backend_srv';
  9. import { DashboardSrv } from '../dashboard/services/DashboardSrv';
  10. import DatasourceSrv from '../plugins/datasource_srv';
  11. import { DataQuery } from '@grafana/ui/src/types/datasource';
  12. import { PanelModel } from 'app/features/dashboard/state';
  13. export class AlertTabCtrl {
  14. panel: PanelModel;
  15. panelCtrl: any;
  16. subTabIndex: number;
  17. conditionTypes: any;
  18. alert: any;
  19. conditionModels: any;
  20. evalFunctions: any;
  21. evalOperators: any;
  22. noDataModes: any;
  23. executionErrorModes: any;
  24. addNotificationSegment: any;
  25. notifications: any;
  26. alertNotifications: any;
  27. error: string;
  28. appSubUrl: string;
  29. alertHistory: any;
  30. /** @ngInject */
  31. constructor(
  32. private $scope: any,
  33. private backendSrv: BackendSrv,
  34. private dashboardSrv: DashboardSrv,
  35. private uiSegmentSrv: any,
  36. private $q: any,
  37. private datasourceSrv: DatasourceSrv
  38. ) {
  39. this.panelCtrl = $scope.ctrl;
  40. this.panel = this.panelCtrl.panel;
  41. this.$scope.ctrl = this;
  42. this.subTabIndex = 0;
  43. this.evalFunctions = alertDef.evalFunctions;
  44. this.evalOperators = alertDef.evalOperators;
  45. this.conditionTypes = alertDef.conditionTypes;
  46. this.noDataModes = alertDef.noDataModes;
  47. this.executionErrorModes = alertDef.executionErrorModes;
  48. this.appSubUrl = config.appSubUrl;
  49. this.panelCtrl._enableAlert = this.enable;
  50. }
  51. $onInit() {
  52. this.addNotificationSegment = this.uiSegmentSrv.newPlusButton();
  53. // subscribe to graph threshold handle changes
  54. const thresholdChangedEventHandler = this.graphThresholdChanged.bind(this);
  55. this.panelCtrl.events.on('threshold-changed', thresholdChangedEventHandler);
  56. // set panel alert edit mode
  57. this.$scope.$on('$destroy', () => {
  58. this.panelCtrl.events.off('threshold-changed', thresholdChangedEventHandler);
  59. this.panelCtrl.editingThresholds = false;
  60. this.panelCtrl.render();
  61. });
  62. // build notification model
  63. this.notifications = [];
  64. this.alertNotifications = [];
  65. this.alertHistory = [];
  66. return this.backendSrv.get('/api/alert-notifications').then((res: any) => {
  67. this.notifications = res;
  68. this.initModel();
  69. this.validateModel();
  70. });
  71. }
  72. getAlertHistory() {
  73. this.backendSrv
  74. .get(`/api/annotations?dashboardId=${this.panelCtrl.dashboard.id}&panelId=${this.panel.id}&limit=50&type=alert`)
  75. .then((res: any) => {
  76. this.alertHistory = _.map(res, ah => {
  77. ah.time = this.dashboardSrv.getCurrent().formatDate(ah.time, 'MMM D, YYYY HH:mm:ss');
  78. ah.stateModel = alertDef.getStateDisplayModel(ah.newState);
  79. ah.info = alertDef.getAlertAnnotationInfo(ah);
  80. return ah;
  81. });
  82. });
  83. }
  84. getNotificationIcon(type: string): string {
  85. switch (type) {
  86. case 'email':
  87. return 'fa fa-envelope';
  88. case 'slack':
  89. return 'fa fa-slack';
  90. case 'victorops':
  91. return 'fa fa-pagelines';
  92. case 'webhook':
  93. return 'fa fa-cubes';
  94. case 'pagerduty':
  95. return 'fa fa-bullhorn';
  96. case 'opsgenie':
  97. return 'fa fa-bell';
  98. case 'hipchat':
  99. return 'fa fa-mail-forward';
  100. case 'pushover':
  101. return 'fa fa-mobile';
  102. case 'kafka':
  103. return 'fa fa-random';
  104. case 'teams':
  105. return 'fa fa-windows';
  106. }
  107. return 'fa fa-bell';
  108. }
  109. getNotifications() {
  110. return this.$q.when(
  111. this.notifications.map((item: any) => {
  112. return this.uiSegmentSrv.newSegment(item.name);
  113. })
  114. );
  115. }
  116. notificationAdded() {
  117. const model: any = _.find(this.notifications, {
  118. name: this.addNotificationSegment.value,
  119. });
  120. if (!model) {
  121. return;
  122. }
  123. this.alertNotifications.push({
  124. name: model.name,
  125. iconClass: this.getNotificationIcon(model.type),
  126. isDefault: false,
  127. uid: model.uid,
  128. });
  129. // avoid duplicates using both id and uid to be backwards compatible.
  130. if (!_.find(this.alert.notifications, n => n.id === model.id || n.uid === model.uid)) {
  131. this.alert.notifications.push({ uid: model.uid });
  132. }
  133. // reset plus button
  134. this.addNotificationSegment.value = this.uiSegmentSrv.newPlusButton().value;
  135. this.addNotificationSegment.html = this.uiSegmentSrv.newPlusButton().html;
  136. this.addNotificationSegment.fake = true;
  137. }
  138. removeNotification(an: any) {
  139. // remove notifiers refeered to by id and uid to support notifiers added
  140. // before and after we added support for uid
  141. _.remove(this.alert.notifications, (n: any) => n.uid === an.uid || n.id === an.id);
  142. _.remove(this.alertNotifications, (n: any) => n.uid === an.uid || n.id === an.id);
  143. }
  144. initModel() {
  145. const alert = (this.alert = this.panel.alert);
  146. if (!alert) {
  147. return;
  148. }
  149. alert.conditions = alert.conditions || [];
  150. if (alert.conditions.length === 0) {
  151. alert.conditions.push(this.buildDefaultCondition());
  152. }
  153. alert.noDataState = alert.noDataState || config.alertingNoDataOrNullValues;
  154. alert.executionErrorState = alert.executionErrorState || config.alertingErrorOrTimeout;
  155. alert.frequency = alert.frequency || '1m';
  156. alert.handler = alert.handler || 1;
  157. alert.notifications = alert.notifications || [];
  158. alert.for = alert.for || '0m';
  159. const defaultName = this.panel.title + ' alert';
  160. alert.name = alert.name || defaultName;
  161. this.conditionModels = _.reduce(
  162. alert.conditions,
  163. (memo, value) => {
  164. memo.push(this.buildConditionModel(value));
  165. return memo;
  166. },
  167. []
  168. );
  169. ThresholdMapper.alertToGraphThresholds(this.panel);
  170. for (const addedNotification of alert.notifications) {
  171. // lookup notifier type by uid
  172. let model: any = _.find(this.notifications, { uid: addedNotification.uid });
  173. // fallback to using id if uid is missing
  174. if (!model) {
  175. model = _.find(this.notifications, { id: addedNotification.id });
  176. }
  177. if (model && model.isDefault === false) {
  178. model.iconClass = this.getNotificationIcon(model.type);
  179. this.alertNotifications.push(model);
  180. }
  181. }
  182. for (const notification of this.notifications) {
  183. if (notification.isDefault) {
  184. notification.iconClass = this.getNotificationIcon(notification.type);
  185. notification.bgColor = '#00678b';
  186. this.alertNotifications.push(notification);
  187. }
  188. }
  189. this.panelCtrl.editingThresholds = true;
  190. this.panelCtrl.render();
  191. }
  192. graphThresholdChanged(evt: any) {
  193. for (const condition of this.alert.conditions) {
  194. if (condition.type === 'query') {
  195. condition.evaluator.params[evt.handleIndex] = evt.threshold.value;
  196. this.evaluatorParamsChanged();
  197. break;
  198. }
  199. }
  200. }
  201. buildDefaultCondition() {
  202. return {
  203. type: 'query',
  204. query: { params: ['A', '5m', 'now'] },
  205. reducer: { type: 'avg', params: [] as any[] },
  206. evaluator: { type: 'gt', params: [null] as any[] },
  207. operator: { type: 'and' },
  208. };
  209. }
  210. validateModel() {
  211. if (!this.alert) {
  212. return;
  213. }
  214. let firstTarget;
  215. let foundTarget: DataQuery = null;
  216. for (const condition of this.alert.conditions) {
  217. if (condition.type !== 'query') {
  218. continue;
  219. }
  220. for (const target of this.panel.targets) {
  221. if (!firstTarget) {
  222. firstTarget = target;
  223. }
  224. if (condition.query.params[0] === target.refId) {
  225. foundTarget = target;
  226. break;
  227. }
  228. }
  229. if (!foundTarget) {
  230. if (firstTarget) {
  231. condition.query.params[0] = firstTarget.refId;
  232. foundTarget = firstTarget;
  233. } else {
  234. this.error = 'Could not find any metric queries';
  235. }
  236. }
  237. const datasourceName = foundTarget.datasource || this.panel.datasource;
  238. this.datasourceSrv.get(datasourceName).then(ds => {
  239. if (!ds.meta.alerting) {
  240. this.error = 'The datasource does not support alerting queries';
  241. } else if (ds.targetContainsTemplate && ds.targetContainsTemplate(foundTarget)) {
  242. this.error = 'Template variables are not supported in alert queries';
  243. } else {
  244. this.error = '';
  245. }
  246. });
  247. }
  248. }
  249. buildConditionModel(source: any) {
  250. const cm: any = { source: source, type: source.type };
  251. cm.queryPart = new QueryPart(source.query, alertDef.alertQueryDef);
  252. cm.reducerPart = alertDef.createReducerPart(source.reducer);
  253. cm.evaluator = source.evaluator;
  254. cm.operator = source.operator;
  255. return cm;
  256. }
  257. handleQueryPartEvent(conditionModel: any, evt: any) {
  258. switch (evt.name) {
  259. case 'action-remove-part': {
  260. break;
  261. }
  262. case 'get-part-actions': {
  263. return this.$q.when([]);
  264. }
  265. case 'part-param-changed': {
  266. this.validateModel();
  267. }
  268. case 'get-param-options': {
  269. const result = this.panel.targets.map(target => {
  270. return this.uiSegmentSrv.newSegment({ value: target.refId });
  271. });
  272. return this.$q.when(result);
  273. }
  274. }
  275. }
  276. handleReducerPartEvent(conditionModel: any, evt: any) {
  277. switch (evt.name) {
  278. case 'action': {
  279. conditionModel.source.reducer.type = evt.action.value;
  280. conditionModel.reducerPart = alertDef.createReducerPart(conditionModel.source.reducer);
  281. break;
  282. }
  283. case 'get-part-actions': {
  284. const result = [];
  285. for (const type of alertDef.reducerTypes) {
  286. if (type.value !== conditionModel.source.reducer.type) {
  287. result.push(type);
  288. }
  289. }
  290. return this.$q.when(result);
  291. }
  292. }
  293. }
  294. addCondition(type: string) {
  295. const condition = this.buildDefaultCondition();
  296. // add to persited model
  297. this.alert.conditions.push(condition);
  298. // add to view model
  299. this.conditionModels.push(this.buildConditionModel(condition));
  300. }
  301. removeCondition(index: number) {
  302. this.alert.conditions.splice(index, 1);
  303. this.conditionModels.splice(index, 1);
  304. }
  305. delete() {
  306. appEvents.emit('confirm-modal', {
  307. title: 'Delete Alert',
  308. text: 'Are you sure you want to delete this alert rule?',
  309. text2: 'You need to save dashboard for the delete to take effect',
  310. icon: 'fa-trash',
  311. yesText: 'Delete',
  312. onConfirm: () => {
  313. delete this.panel.alert;
  314. this.alert = null;
  315. this.panel.thresholds = [];
  316. this.conditionModels = [];
  317. this.panelCtrl.alertState = null;
  318. this.panelCtrl.render();
  319. },
  320. });
  321. }
  322. enable = () => {
  323. this.panel.alert = {};
  324. this.initModel();
  325. this.panel.alert.for = '5m'; //default value for new alerts. for existing alerts we use 0m to avoid breaking changes
  326. };
  327. evaluatorParamsChanged() {
  328. ThresholdMapper.alertToGraphThresholds(this.panel);
  329. this.panelCtrl.render();
  330. }
  331. evaluatorTypeChanged(evaluator: any) {
  332. // ensure params array is correct length
  333. switch (evaluator.type) {
  334. case 'lt':
  335. case 'gt': {
  336. evaluator.params = [evaluator.params[0]];
  337. break;
  338. }
  339. case 'within_range':
  340. case 'outside_range': {
  341. evaluator.params = [evaluator.params[0], evaluator.params[1]];
  342. break;
  343. }
  344. case 'no_value': {
  345. evaluator.params = [];
  346. }
  347. }
  348. this.evaluatorParamsChanged();
  349. }
  350. clearHistory() {
  351. appEvents.emit('confirm-modal', {
  352. title: 'Delete Alert History',
  353. text: 'Are you sure you want to remove all history & annotations for this alert?',
  354. icon: 'fa-trash',
  355. yesText: 'Yes',
  356. onConfirm: () => {
  357. this.backendSrv
  358. .post('/api/annotations/mass-delete', {
  359. dashboardId: this.panelCtrl.dashboard.id,
  360. panelId: this.panel.id,
  361. })
  362. .then(() => {
  363. this.alertHistory = [];
  364. this.panelCtrl.refresh();
  365. });
  366. },
  367. });
  368. }
  369. }
  370. /** @ngInject */
  371. export function alertTab() {
  372. 'use strict';
  373. return {
  374. restrict: 'E',
  375. scope: true,
  376. templateUrl: 'public/app/features/alerting/partials/alert_tab.html',
  377. controller: AlertTabCtrl,
  378. };
  379. }
  380. coreModule.directive('alertTab', alertTab);