alert_tab_ctrl.ts 9.4 KB

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