alert_tab_ctrl.ts 11 KB

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