alert_tab_ctrl.ts 9.9 KB

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