alert_tab_ctrl.ts 11 KB

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