alert_tab_ctrl.ts 11 KB

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