alert_tab_ctrl.ts 11 KB

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