alert_tab_ctrl.ts 11 KB

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