alert_tab_ctrl.ts 9.8 KB

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