alert_tab_ctrl.ts 11 KB

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