alert_tab_ctrl.ts 11 KB

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