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