alert_tab_ctrl.ts 9.2 KB

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