AlertTabCtrl.ts 11 KB

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