alert_tab_ctrl.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 moment from 'moment';
  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. severityLevels: any;
  19. noDataModes: any;
  20. addNotificationSegment;
  21. notifications;
  22. alertNotifications;
  23. error: string;
  24. appSubUrl: string;
  25. alertHistory: any;
  26. /** @ngInject */
  27. constructor(private $scope,
  28. private $timeout,
  29. private backendSrv,
  30. private dashboardSrv,
  31. private uiSegmentSrv,
  32. private $q,
  33. private datasourceSrv,
  34. private templateSrv) {
  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.conditionTypes = alertDef.conditionTypes;
  41. this.severityLevels = alertDef.severityLevels;
  42. this.noDataModes = alertDef.noDataModes;
  43. this.appSubUrl = config.appSubUrl;
  44. }
  45. $onInit() {
  46. this.addNotificationSegment = this.uiSegmentSrv.newPlusButton();
  47. this.initModel();
  48. this.validateModel();
  49. // set panel alert edit mode
  50. this.$scope.$on("$destroy", () => {
  51. this.panelCtrl.editingThresholds = false;
  52. this.panelCtrl.render();
  53. });
  54. // subscribe to graph threshold handle changes
  55. this.panelCtrl.events.on('threshold-changed', this.graphThresholdChanged.bind(this));
  56. // build notification model
  57. this.notifications = [];
  58. this.alertNotifications = [];
  59. this.alertHistory = [];
  60. return this.backendSrv.get('/api/alert-notifications').then(res => {
  61. this.notifications = res;
  62. _.each(this.alert.notifications, item => {
  63. var model = _.findWhere(this.notifications, {id: item.id});
  64. if (model) {
  65. model.iconClass = this.getNotificationIcon(model.type);
  66. this.alertNotifications.push(model);
  67. }
  68. });
  69. });
  70. }
  71. getAlertHistory() {
  72. this.backendSrv.get(`/api/alert-history?dashboardId=${this.panelCtrl.dashboard.id}&panelId=${this.panel.id}`).then(res => {
  73. this.alertHistory = _.map(res, ah => {
  74. ah.time = moment(ah.timestamp).format('MMM D, YYYY HH:mm:ss');
  75. ah.stateModel = alertDef.getStateDisplayModel(ah.newState);
  76. ah.metrics = _.map(ah.data, ev=> {
  77. return ev.Metric + "=" + ev.Value;
  78. }).join(', ');
  79. return ah;
  80. });
  81. });
  82. }
  83. getNotificationIcon(type) {
  84. switch (type) {
  85. case "email": return "fa fa-envelope";
  86. case "slack": return "fa fa-slack";
  87. case "webhook": return "fa fa-cubes";
  88. }
  89. }
  90. getNotifications() {
  91. return Promise.resolve(this.notifications.map(item => {
  92. return this.uiSegmentSrv.newSegment(item.name);
  93. }));
  94. }
  95. changeTabIndex(newTabIndex) {
  96. this.subTabIndex = newTabIndex;
  97. if (this.subTabIndex === 2) {
  98. this.getAlertHistory();
  99. }
  100. }
  101. notificationAdded() {
  102. var model = _.findWhere(this.notifications, {name: this.addNotificationSegment.value});
  103. if (!model) {
  104. return;
  105. }
  106. this.alertNotifications.push({name: model.name, iconClass: this.getNotificationIcon(model.type)});
  107. this.alert.notifications.push({id: model.id});
  108. // reset plus button
  109. this.addNotificationSegment.value = this.uiSegmentSrv.newPlusButton().value;
  110. this.addNotificationSegment.html = this.uiSegmentSrv.newPlusButton().html;
  111. }
  112. removeNotification(index) {
  113. this.alert.notifications.splice(index, 1);
  114. this.alertNotifications.splice(index, 1);
  115. }
  116. initModel() {
  117. var alert = this.alert = this.panel.alert = this.panel.alert || {enabled: false};
  118. if (!this.alert.enabled) {
  119. return;
  120. }
  121. alert.conditions = alert.conditions || [];
  122. if (alert.conditions.length === 0) {
  123. alert.conditions.push(this.buildDefaultCondition());
  124. }
  125. alert.noDataState = alert.noDataState || 'unknown';
  126. alert.severity = alert.severity || 'critical';
  127. alert.frequency = alert.frequency || '60s';
  128. alert.handler = alert.handler || 1;
  129. alert.notifications = alert.notifications || [];
  130. var defaultName = this.panel.title + ' alert';
  131. alert.name = alert.name || defaultName;
  132. this.conditionModels = _.reduce(alert.conditions, (memo, value) => {
  133. memo.push(this.buildConditionModel(value));
  134. return memo;
  135. }, []);
  136. ThresholdMapper.alertToGraphThresholds(this.panel);
  137. this.panelCtrl.editingThresholds = true;
  138. this.panelCtrl.render();
  139. }
  140. graphThresholdChanged(evt) {
  141. for (var condition of this.alert.conditions) {
  142. if (condition.type === 'query') {
  143. condition.evaluator.params[evt.handleIndex] = evt.threshold.value;
  144. this.evaluatorParamsChanged();
  145. break;
  146. }
  147. }
  148. }
  149. buildDefaultCondition() {
  150. return {
  151. type: 'query',
  152. query: {params: ['A', '5m', 'now']},
  153. reducer: {type: 'avg', params: []},
  154. evaluator: {type: 'gt', params: [null]},
  155. };
  156. }
  157. validateModel() {
  158. if (!this.alert.enabled) {
  159. return;
  160. }
  161. let firstTarget;
  162. var fixed = false;
  163. let foundTarget = null;
  164. for (var condition of this.alert.conditions) {
  165. if (condition.type !== 'query') {
  166. continue;
  167. }
  168. for (var target of this.panel.targets) {
  169. if (!firstTarget) {
  170. firstTarget = target;
  171. }
  172. if (condition.query.params[0] === target.refId) {
  173. foundTarget = target;
  174. break;
  175. }
  176. }
  177. if (!foundTarget) {
  178. if (firstTarget) {
  179. condition.query.params[0] = firstTarget.refId;
  180. foundTarget = firstTarget;
  181. fixed = true;
  182. } else {
  183. this.error = "Could not find any metric queries";
  184. }
  185. }
  186. var datasourceName = foundTarget.datasource || this.panel.datasource;
  187. this.datasourceSrv.get(datasourceName).then(ds => {
  188. if (ds.meta.id !== 'graphite') {
  189. this.error = 'Currently the alerting backend only supports Graphite queries';
  190. } else if (this.templateSrv.variableExists(foundTarget.target)) {
  191. this.error = 'Template variables are not supported in alert queries';
  192. } else {
  193. this.error = '';
  194. }
  195. });
  196. }
  197. }
  198. buildConditionModel(source) {
  199. var cm: any = {source: source, type: source.type};
  200. cm.queryPart = new QueryPart(source.query, alertDef.alertQueryDef);
  201. cm.reducerPart = alertDef.createReducerPart(source.reducer);
  202. cm.evaluator = source.evaluator;
  203. return cm;
  204. }
  205. handleQueryPartEvent(conditionModel, evt) {
  206. switch (evt.name) {
  207. case "action-remove-part": {
  208. break;
  209. }
  210. case "get-part-actions": {
  211. return this.$q.when([]);
  212. }
  213. case "part-param-changed": {
  214. this.validateModel();
  215. }
  216. case "get-param-options": {
  217. var result = this.panel.targets.map(target => {
  218. return this.uiSegmentSrv.newSegment({ value: target.refId });
  219. });
  220. return this.$q.when(result);
  221. }
  222. }
  223. }
  224. handleReducerPartEvent(conditionModel, evt) {
  225. switch (evt.name) {
  226. case "action": {
  227. conditionModel.source.reducer.type = evt.action.value;
  228. conditionModel.reducerPart = alertDef.createReducerPart(conditionModel.source.reducer);
  229. break;
  230. }
  231. case "get-part-actions": {
  232. var result = [];
  233. for (var type of alertDef.reducerTypes) {
  234. if (type.value !== conditionModel.source.reducer.type) {
  235. result.push(type);
  236. }
  237. }
  238. return this.$q.when(result);
  239. }
  240. }
  241. }
  242. addCondition(type) {
  243. var condition = this.buildDefaultCondition();
  244. // add to persited model
  245. this.alert.conditions.push(condition);
  246. // add to view model
  247. this.conditionModels.push(this.buildConditionModel(condition));
  248. }
  249. removeCondition(index) {
  250. this.alert.conditions.splice(index, 1);
  251. this.conditionModels.splice(index, 1);
  252. }
  253. delete() {
  254. this.alert = this.panel.alert = {enabled: false};
  255. this.panel.thresholds = [];
  256. this.conditionModels = [];
  257. this.panelCtrl.render();
  258. }
  259. enable() {
  260. this.alert.enabled = true;
  261. this.initModel();
  262. }
  263. evaluatorParamsChanged() {
  264. ThresholdMapper.alertToGraphThresholds(this.panel);
  265. this.panelCtrl.render();
  266. }
  267. severityChanged() {
  268. ThresholdMapper.alertToGraphThresholds(this.panel);
  269. this.panelCtrl.render();
  270. }
  271. evaluatorTypeChanged(evaluator) {
  272. // ensure params array is correct length
  273. switch (evaluator.type) {
  274. case "lt":
  275. case "gt": {
  276. evaluator.params = [evaluator.params[0]];
  277. break;
  278. }
  279. case "within_range":
  280. case "outside_range": {
  281. evaluator.params = [evaluator.params[0], evaluator.params[1]];
  282. break;
  283. }
  284. case "no_value": {
  285. evaluator.params = [];
  286. }
  287. }
  288. this.evaluatorParamsChanged();
  289. }
  290. test() {
  291. this.testing = true;
  292. var payload = {
  293. dashboard: this.dashboardSrv.getCurrent().getSaveModelClone(),
  294. panelId: this.panelCtrl.panel.id,
  295. };
  296. return this.backendSrv.post('/api/alerts/test', payload).then(res => {
  297. this.testResult = res;
  298. this.testing = false;
  299. });
  300. }
  301. }
  302. /** @ngInject */
  303. export function alertTab() {
  304. 'use strict';
  305. return {
  306. restrict: 'E',
  307. scope: true,
  308. templateUrl: 'public/app/features/alerting/partials/alert_tab.html',
  309. controller: AlertTabCtrl,
  310. };
  311. }