AlertTabCtrl.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 Promise.resolve(
  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. }
  136. removeNotification(index) {
  137. this.alert.notifications.splice(index, 1);
  138. this.alertNotifications.splice(index, 1);
  139. }
  140. initModel() {
  141. const alert = (this.alert = this.panel.alert);
  142. if (!alert) {
  143. return;
  144. }
  145. alert.conditions = alert.conditions || [];
  146. if (alert.conditions.length === 0) {
  147. alert.conditions.push(this.buildDefaultCondition());
  148. }
  149. alert.noDataState = alert.noDataState || config.alertingNoDataOrNullValues;
  150. alert.executionErrorState = alert.executionErrorState || config.alertingErrorOrTimeout;
  151. alert.frequency = alert.frequency || '1m';
  152. alert.handler = alert.handler || 1;
  153. alert.notifications = alert.notifications || [];
  154. alert.for = alert.for || '0m';
  155. const defaultName = this.panel.title + ' alert';
  156. alert.name = alert.name || defaultName;
  157. this.conditionModels = _.reduce(
  158. alert.conditions,
  159. (memo, value) => {
  160. memo.push(this.buildConditionModel(value));
  161. return memo;
  162. },
  163. []
  164. );
  165. ThresholdMapper.alertToGraphThresholds(this.panel);
  166. for (const addedNotification of alert.notifications) {
  167. const model = _.find(this.notifications, { id: addedNotification.id });
  168. if (model && model.isDefault === false) {
  169. model.iconClass = this.getNotificationIcon(model.type);
  170. this.alertNotifications.push(model);
  171. }
  172. }
  173. for (const notification of this.notifications) {
  174. if (notification.isDefault) {
  175. notification.iconClass = this.getNotificationIcon(notification.type);
  176. notification.bgColor = '#00678b';
  177. this.alertNotifications.push(notification);
  178. }
  179. }
  180. this.panelCtrl.editingThresholds = true;
  181. this.panelCtrl.render();
  182. }
  183. graphThresholdChanged(evt) {
  184. for (const condition of this.alert.conditions) {
  185. if (condition.type === 'query') {
  186. condition.evaluator.params[evt.handleIndex] = evt.threshold.value;
  187. this.evaluatorParamsChanged();
  188. break;
  189. }
  190. }
  191. }
  192. buildDefaultCondition() {
  193. return {
  194. type: 'query',
  195. query: { params: ['A', '5m', 'now'] },
  196. reducer: { type: 'avg', params: [] },
  197. evaluator: { type: 'gt', params: [null] },
  198. operator: { type: 'and' },
  199. };
  200. }
  201. validateModel() {
  202. if (!this.alert) {
  203. return;
  204. }
  205. let firstTarget;
  206. let foundTarget = null;
  207. for (const condition of this.alert.conditions) {
  208. if (condition.type !== 'query') {
  209. continue;
  210. }
  211. for (const target of this.panel.targets) {
  212. if (!firstTarget) {
  213. firstTarget = target;
  214. }
  215. if (condition.query.params[0] === target.refId) {
  216. foundTarget = target;
  217. break;
  218. }
  219. }
  220. if (!foundTarget) {
  221. if (firstTarget) {
  222. condition.query.params[0] = firstTarget.refId;
  223. foundTarget = firstTarget;
  224. } else {
  225. this.error = 'Could not find any metric queries';
  226. }
  227. }
  228. const datasourceName = foundTarget.datasource || this.panel.datasource;
  229. this.datasourceSrv.get(datasourceName).then(ds => {
  230. if (!ds.meta.alerting) {
  231. this.error = 'The datasource does not support alerting queries';
  232. } else if (ds.targetContainsTemplate && ds.targetContainsTemplate(foundTarget)) {
  233. this.error = 'Template variables are not supported in alert queries';
  234. } else {
  235. this.error = '';
  236. }
  237. });
  238. }
  239. }
  240. buildConditionModel(source) {
  241. const cm: any = { source: source, type: source.type };
  242. cm.queryPart = new QueryPart(source.query, alertDef.alertQueryDef);
  243. cm.reducerPart = alertDef.createReducerPart(source.reducer);
  244. cm.evaluator = source.evaluator;
  245. cm.operator = source.operator;
  246. return cm;
  247. }
  248. handleQueryPartEvent(conditionModel, evt) {
  249. switch (evt.name) {
  250. case 'action-remove-part': {
  251. break;
  252. }
  253. case 'get-part-actions': {
  254. return this.$q.when([]);
  255. }
  256. case 'part-param-changed': {
  257. this.validateModel();
  258. }
  259. case 'get-param-options': {
  260. const result = this.panel.targets.map(target => {
  261. return this.uiSegmentSrv.newSegment({ value: target.refId });
  262. });
  263. return this.$q.when(result);
  264. }
  265. }
  266. }
  267. handleReducerPartEvent(conditionModel, evt) {
  268. switch (evt.name) {
  269. case 'action': {
  270. conditionModel.source.reducer.type = evt.action.value;
  271. conditionModel.reducerPart = alertDef.createReducerPart(conditionModel.source.reducer);
  272. break;
  273. }
  274. case 'get-part-actions': {
  275. const result = [];
  276. for (const type of alertDef.reducerTypes) {
  277. if (type.value !== conditionModel.source.reducer.type) {
  278. result.push(type);
  279. }
  280. }
  281. return this.$q.when(result);
  282. }
  283. }
  284. }
  285. addCondition(type) {
  286. const condition = this.buildDefaultCondition();
  287. // add to persited model
  288. this.alert.conditions.push(condition);
  289. // add to view model
  290. this.conditionModels.push(this.buildConditionModel(condition));
  291. }
  292. removeCondition(index) {
  293. this.alert.conditions.splice(index, 1);
  294. this.conditionModels.splice(index, 1);
  295. }
  296. delete() {
  297. appEvents.emit('confirm-modal', {
  298. title: 'Delete Alert',
  299. text: 'Are you sure you want to delete this alert rule?',
  300. text2: 'You need to save dashboard for the delete to take effect',
  301. icon: 'fa-trash',
  302. yesText: 'Delete',
  303. onConfirm: () => {
  304. delete this.panel.alert;
  305. this.alert = null;
  306. this.panel.thresholds = [];
  307. this.conditionModels = [];
  308. this.panelCtrl.alertState = null;
  309. this.panelCtrl.render();
  310. },
  311. });
  312. }
  313. enable = () => {
  314. this.panel.alert = {};
  315. this.initModel();
  316. this.panel.alert.for = '5m'; //default value for new alerts. for existing alerts we use 0m to avoid breaking changes
  317. };
  318. evaluatorParamsChanged() {
  319. ThresholdMapper.alertToGraphThresholds(this.panel);
  320. this.panelCtrl.render();
  321. }
  322. evaluatorTypeChanged(evaluator) {
  323. // ensure params array is correct length
  324. switch (evaluator.type) {
  325. case 'lt':
  326. case 'gt': {
  327. evaluator.params = [evaluator.params[0]];
  328. break;
  329. }
  330. case 'within_range':
  331. case 'outside_range': {
  332. evaluator.params = [evaluator.params[0], evaluator.params[1]];
  333. break;
  334. }
  335. case 'no_value': {
  336. evaluator.params = [];
  337. }
  338. }
  339. this.evaluatorParamsChanged();
  340. }
  341. clearHistory() {
  342. appEvents.emit('confirm-modal', {
  343. title: 'Delete Alert History',
  344. text: 'Are you sure you want to remove all history & annotations for this alert?',
  345. icon: 'fa-trash',
  346. yesText: 'Yes',
  347. onConfirm: () => {
  348. this.backendSrv
  349. .post('/api/annotations/mass-delete', {
  350. dashboardId: this.panelCtrl.dashboard.id,
  351. panelId: this.panel.id,
  352. })
  353. .then(res => {
  354. this.alertHistory = [];
  355. this.panelCtrl.refresh();
  356. });
  357. },
  358. });
  359. }
  360. test() {
  361. this.testing = true;
  362. this.testResult = false;
  363. const payload = {
  364. dashboard: this.dashboardSrv.getCurrent().getSaveModelClone(),
  365. panelId: this.panelCtrl.panel.id,
  366. };
  367. return this.backendSrv.post('/api/alerts/test', payload).then(res => {
  368. this.testResult = res;
  369. this.testing = false;
  370. });
  371. }
  372. }
  373. /** @ngInject */
  374. export function alertTab() {
  375. 'use strict';
  376. return {
  377. restrict: 'E',
  378. scope: true,
  379. templateUrl: 'public/app/features/alerting/partials/alert_tab.html',
  380. controller: AlertTabCtrl,
  381. };
  382. }
  383. coreModule.directive('alertTab', alertTab);