alert_tab_ctrl.ts 9.6 KB

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