alert_tab_ctrl.ts 11 KB

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