alert_tab_ctrl.ts 11 KB

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