alert_tab_ctrl.ts 11 KB

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