AlertTabCtrl.ts 12 KB

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