AlertTabCtrl.ts 11 KB

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