alert_tab_ctrl.ts 10.0 KB

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