alert_tab_ctrl.ts 9.8 KB

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