AlertTabCtrl.ts 12 KB

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