AlertTabCtrl.ts 12 KB

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