widget_mixin.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. var App = require('app');
  19. var stringUtils = require('utils/string_utils');
  20. App.WidgetMixin = Ember.Mixin.create({
  21. /**
  22. * type of metric query from which the widget is comprised
  23. */
  24. metricType: 'POINT_IN_TIME',
  25. /**
  26. * @type {RegExp}
  27. * @const
  28. */
  29. EXPRESSION_REGEX: /\$\{([\w\s\.\,\+\-\*\/\(\)\:\=\[\]]*)\}/g,
  30. /**
  31. * @type {RegExp}
  32. * @const
  33. */
  34. MATH_EXPRESSION_REGEX: /^[\d\s\+\-\*\/\(\)\.]+$/,
  35. /**
  36. * @type {RegExp}
  37. * @const
  38. */
  39. VALUE_NAME_REGEX: /(\w+\s+\w+)?[\w\.\,\:\=\[\]]+/g,
  40. /**
  41. * @type {string}
  42. * @const
  43. */
  44. CLONE_SUFFIX: '(Copy)',
  45. /**
  46. * @type {number|null}
  47. */
  48. timeoutId: null,
  49. /**
  50. * common metrics container
  51. * @type {Array}
  52. */
  53. metrics: [],
  54. /**
  55. *
  56. */
  57. aggregatorFunc: ['._sum', '._avg', '._min', '._max'],
  58. /**
  59. * @type {boolean}
  60. */
  61. isLoaded: false,
  62. /**
  63. * @type {App.Widget}
  64. * @default null
  65. */
  66. content: null,
  67. /**
  68. * color of content calculated by thresholds
  69. * @type {string}
  70. */
  71. contentColor: Em.computed.ifThenElse('value', 'green', 'grey'),
  72. beforeRender: function () {
  73. this.get('metrics').clear();
  74. this.loadMetrics();
  75. },
  76. /**
  77. * load metrics
  78. */
  79. loadMetrics: function () {
  80. var requestData = this.getRequestData(this.get('content.metrics')),
  81. request,
  82. requestCounter = 0,
  83. self = this;
  84. for (var i in requestData) {
  85. request = requestData[i];
  86. requestCounter++;
  87. if (this.get('content.widgetType') === 'HEATMAP') {
  88. if (request.service_name === 'STACK') {
  89. this.getHostsMetrics(request).complete(function () {
  90. requestCounter--;
  91. if (requestCounter === 0) self.onMetricsLoaded();
  92. });
  93. } else {
  94. this.getHostComponentsMetrics(request).complete(function () {
  95. requestCounter--;
  96. if (requestCounter === 0) self.onMetricsLoaded();
  97. });
  98. }
  99. } else if (request.host_component_criteria) {
  100. App.WidgetLoadAggregator.add({
  101. data: request,
  102. context: this,
  103. startCallName: 'getHostComponentMetrics',
  104. successCallback: this.getHostComponentMetricsSuccessCallback,
  105. errorCallback: this.getMetricsErrorCallback,
  106. completeCallback: function (xhr) {
  107. requestCounter--;
  108. if (requestCounter === 0) this.onMetricsLoaded();
  109. if (this.get('graphView')) {
  110. var graph = this.get('childViews') && this.get('childViews').findProperty('runningRequests');
  111. if (graph) {
  112. var requestsArrayName = graph.get('isPopup') ? 'runningPopupRequests' : 'runningRequests';
  113. graph.set(requestsArrayName, graph.get(requestsArrayName).reject(function (item) {
  114. return item === xhr;
  115. }));
  116. }
  117. }
  118. }
  119. });
  120. } else {
  121. App.WidgetLoadAggregator.add({
  122. data: request,
  123. context: this,
  124. startCallName: 'getServiceComponentMetrics',
  125. successCallback: this.getMetricsSuccessCallback,
  126. errorCallback: this.getMetricsErrorCallback,
  127. completeCallback: function (xhr) {
  128. requestCounter--;
  129. if (requestCounter === 0) this.onMetricsLoaded();
  130. if (this.get('graphView')) {
  131. var graph = this.get('childViews') && this.get('childViews').findProperty('runningRequests');
  132. if (graph) {
  133. var requestsArrayName = graph.get('isPopup') ? 'runningPopupRequests' : 'runningRequests';
  134. graph.set(requestsArrayName, graph.get(requestsArrayName).reject(function (item) {
  135. return item === xhr;
  136. }));
  137. }
  138. }
  139. }
  140. });
  141. }
  142. }
  143. }.observes('customTimeRange', 'content.properties.time_range'),
  144. /**
  145. * get data formatted for request
  146. * @param {Array} metrics
  147. */
  148. getRequestData: function (metrics) {
  149. var requestsData = {};
  150. if (metrics) {
  151. metrics.forEach(function (metric, index) {
  152. var key;
  153. if (metric.host_component_criteria) {
  154. key = metric.service_name + '_' + metric.component_name + '_' + metric.host_component_criteria;
  155. } else {
  156. key = metric.service_name + '_' + metric.component_name;
  157. }
  158. var requestMetric = $.extend({}, metric);
  159. if (requestsData[key]) {
  160. requestsData[key]["metric_paths"].push({
  161. metric_path: requestMetric["metric_path"],
  162. metric_type: this.get('metricType'),
  163. id: requestMetric["metric_path"] + "_" + this.get('metricType'),
  164. context: this
  165. });
  166. } else {
  167. requestMetric["metric_paths"] = [{
  168. metric_path: requestMetric["metric_path"],
  169. metric_type: this.get('metricType'),
  170. id: requestMetric["metric_path"] + "_" + this.get('metricType'),
  171. context: this}];
  172. delete requestMetric["metric_path"];
  173. requestsData[key] = requestMetric;
  174. }
  175. }, this);
  176. }
  177. return requestsData;
  178. },
  179. /**
  180. * Tweak host component criteria from the actual host component criteria
  181. * @param {object} request
  182. */
  183. computeHostComponentCriteria: function (request) {
  184. return request.host_component_criteria.replace('host_components/', '&').trim();
  185. },
  186. /**
  187. * make GET call to server in order to fetch service-component metrics
  188. * @param {object} request
  189. * @returns {$.ajax}
  190. */
  191. getServiceComponentMetrics: function (request) {
  192. var xhr = App.ajax.send({
  193. name: 'widgets.serviceComponent.metrics.get',
  194. sender: this,
  195. data: {
  196. serviceName: request.service_name,
  197. componentName: request.component_name,
  198. metricPaths: this.prepareMetricPaths(request.metric_paths)
  199. }
  200. });
  201. if (this.get('graphView')) {
  202. var graph = this.get('childViews') && this.get('childViews').findProperty('runningRequests');
  203. if (graph) {
  204. var requestsArrayName = graph.get('isPopup') ? 'runningPopupRequests' : 'runningRequests';
  205. graph.get(requestsArrayName).push(xhr);
  206. }
  207. }
  208. return xhr;
  209. },
  210. /**
  211. * aggregate all metric names in the query. Add time range and step to temporal queries
  212. * @param {Array} metricPaths
  213. * @returns {string}
  214. */
  215. prepareMetricPaths: function(metricPaths) {
  216. var temporalMetrics = metricPaths.filterProperty('metric_type', 'TEMPORAL');
  217. var pointInTimeMetrics = metricPaths.filterProperty('metric_type', 'POINT_IN_TIME');
  218. var result = temporalMetrics.length ? temporalMetrics[0].context.addTimeProperties(temporalMetrics.mapProperty('metric_path')) : [];
  219. if (pointInTimeMetrics.length) {
  220. result = result.concat(pointInTimeMetrics.mapProperty('metric_path'));
  221. }
  222. return result.join(',');
  223. },
  224. /**
  225. * make GET call to server in order to fetch specific host-component metrics
  226. * @param {object} request
  227. * @returns {$.ajax}
  228. */
  229. getHostComponentMetrics: function (request) {
  230. var metricPaths = this.prepareMetricPaths(request.metric_paths);
  231. if (metricPaths.length) {
  232. var xhr = App.ajax.send({
  233. name: 'widgets.hostComponent.metrics.get',
  234. sender: this,
  235. data: {
  236. componentName: request.component_name,
  237. metricPaths: this.prepareMetricPaths(request.metric_paths),
  238. hostComponentCriteria: this.computeHostComponentCriteria(request)
  239. }
  240. }),
  241. graph = this.get('graphView') && this.get('childViews') && this.get('childViews').findProperty('runningRequests');
  242. if (graph) {
  243. var requestsArrayName = graph.get('isPopup') ? 'runningPopupRequests' : 'runningRequests';
  244. graph.get(requestsArrayName).push(xhr);
  245. }
  246. return xhr;
  247. }
  248. return jQuery.Deferred().reject().promise();
  249. },
  250. getHostComponentMetricsSuccessCallback: function (data) {
  251. if (data.items[0]) {
  252. this.getMetricsSuccessCallback(data.items[0]);
  253. }
  254. },
  255. /**
  256. * callback on getting aggregated metrics and host component metrics
  257. * @param data
  258. */
  259. getMetricsSuccessCallback: function (data) {
  260. var metrics = [];
  261. if (this.get('content.metrics')) {
  262. this.get('content.metrics').forEach(function (_metric) {
  263. var metric_path = _metric.metric_path;
  264. var isAggregatorFunc = false;
  265. var metric_data = Em.get(data, metric_path.replace(/\//g, '.'));
  266. if (Em.isNone(metric_data)) {
  267. this.aggregatorFunc.forEach(function (_item) {
  268. if (metric_path.endsWith(_item) && !isAggregatorFunc) {
  269. isAggregatorFunc = true;
  270. var metricBeanProperty = metric_path.split("/").pop();
  271. var metricBean;
  272. metric_path = metric_path.substring(0, metric_path.indexOf(metricBeanProperty));
  273. if (metric_path.endsWith("/")) {
  274. metric_path = metric_path.slice(0, -1);
  275. }
  276. metricBean = Em.get(data, metric_path.replace(/\//g, '.'));
  277. if (!Em.isNone(metricBean)) {
  278. metric_data = metricBean[metricBeanProperty];
  279. }
  280. }
  281. }, this);
  282. }
  283. if (!Em.isNone(metric_data)) {
  284. _metric.data = metric_data;
  285. this.get('metrics').pushObject(_metric);
  286. } else if (this.get('graphView')) {
  287. var graph = this.get('childViews') && this.get('childViews').findProperty('_showMessage');
  288. if (graph) {
  289. graph.set('hasData', false);
  290. this.set('isExportButtonHidden', true);
  291. graph._showMessage('info', this.t('graphs.noData.title'), this.t('graphs.noDataAtTime.message'));
  292. this.set('metrics', this.get('metrics').reject(function (item) {
  293. return this.get('content.metrics').someProperty('name', item.name);
  294. }, this));
  295. }
  296. }
  297. }, this);
  298. }
  299. },
  300. /**
  301. * error callback on getting aggregated metrics and host component metrics
  302. * @param {object} xhr
  303. * @param {string} textStatus
  304. * @param {string} errorThrown
  305. */
  306. getMetricsErrorCallback: function (xhr, textStatus, errorThrown) {
  307. if (this.get('graphView') && !xhr.isForcedAbort) {
  308. var graph = this.get('childViews') && this.get('childViews').findProperty('_showMessage');
  309. if (graph) {
  310. if (xhr.readyState == 4 && xhr.status) {
  311. textStatus = xhr.status + " " + textStatus;
  312. }
  313. graph.set('hasData', false);
  314. this.set('isExportButtonHidden', true);
  315. graph._showMessage('warn', this.t('graphs.error.title'), this.t('graphs.error.message').format(textStatus, errorThrown));
  316. this.set('metrics', this.get('metrics').reject(function (item) {
  317. return this.get('content.metrics').someProperty('name', item.name);
  318. }, this));
  319. }
  320. }
  321. },
  322. /**
  323. * make GET call to get metrics value for all host components
  324. * @param {object} request
  325. * @return {$.ajax}
  326. */
  327. getHostComponentsMetrics: function (request) {
  328. request.metric_paths.forEach(function (_metric, index) {
  329. request.metric_paths[index] = "host_components/" + _metric.metric_path;
  330. });
  331. return App.ajax.send({
  332. name: 'widgets.serviceComponent.metrics.get',
  333. sender: this,
  334. data: {
  335. serviceName: request.service_name,
  336. componentName: request.component_name,
  337. metricPaths: request.metric_paths.join(',')
  338. },
  339. success: 'getHostComponentsMetricsSuccessCallback'
  340. });
  341. },
  342. getHostComponentsMetricsSuccessCallback: function (data) {
  343. var metrics = this.get('content.metrics');
  344. data.host_components.forEach(function (item) {
  345. metrics.forEach(function (_metric) {
  346. if (!Em.isNone(Em.get(item, _metric.metric_path.replace(/\//g, '.')))) {
  347. var metric = $.extend({}, _metric, true);
  348. metric.data = Em.get(item, _metric.metric_path.replace(/\//g, '.'));
  349. metric.hostName = item.HostRoles.host_name;
  350. this.get('metrics').pushObject(metric);
  351. }
  352. }, this);
  353. }, this);
  354. },
  355. getHostsMetrics: function (request) {
  356. var metricPaths = request.metric_paths.mapProperty('metric_path');
  357. return App.ajax.send({
  358. name: 'widgets.hosts.metrics.get',
  359. sender: this,
  360. data: {
  361. metricPaths: metricPaths.join(',')
  362. },
  363. success: 'getHostsMetricsSuccessCallback'
  364. });
  365. },
  366. getHostsMetricsSuccessCallback: function (data) {
  367. var metrics = this.get('content.metrics');
  368. data.items.forEach(function (item) {
  369. metrics.forEach(function (_metric, index) {
  370. if (!Em.isNone(Em.get(item, _metric.metric_path.replace(/\//g, '.')))) {
  371. var metric = $.extend({}, _metric, true);
  372. metric.data = Em.get(item, _metric.metric_path.replace(/\//g, '.'));
  373. metric.hostName = item.Hosts.host_name;
  374. this.get('metrics').pushObject(metric);
  375. }
  376. }, this);
  377. }, this);
  378. },
  379. /**
  380. * callback on metrics loaded
  381. */
  382. onMetricsLoaded: function () {
  383. var self = this;
  384. if (!this.get('isLoaded')) this.set('isLoaded', true);
  385. this.drawWidget();
  386. clearTimeout(this.get('timeoutId'));
  387. this.set('timeoutId', setTimeout(function () {
  388. self.loadMetrics();
  389. }, App.contentUpdateInterval));
  390. },
  391. /**
  392. * draw widget
  393. */
  394. drawWidget: function () {
  395. if (this.get('isLoaded')) {
  396. this.calculateValues();
  397. this.set('value', (this.get('content.values')[0]) ? this.get('content.values')[0].computedValue : '');
  398. }
  399. },
  400. /**
  401. * initialize tooltips
  402. */
  403. initTooltip: function () {
  404. var self = this;
  405. if (this.get('isLoaded')) {
  406. Em.run.next(function(){
  407. App.tooltip(self.$(".corner-icon > .icon-copy"), {title: Em.I18n.t('common.clone')});
  408. App.tooltip(self.$(".corner-icon > .icon-edit"), {title: Em.I18n.t('common.edit')});
  409. App.tooltip(self.$(".corner-icon > .icon-save"), {title: Em.I18n.t('common.export')});
  410. });
  411. }
  412. }.observes('isLoaded'),
  413. willDestroyElement: function() {
  414. this.$(".corner-icon > .icon-copy").tooltip('destroy');
  415. this.$(".corner-icon > .icon-edit").tooltip('destroy');
  416. this.$(".corner-icon > .icon-save").tooltip('destroy');
  417. },
  418. /**
  419. * calculate series datasets for graph widgets
  420. */
  421. calculateValues: function () {
  422. this.get('content.values').forEach(function (value) {
  423. var computeExpression = this.computeExpression(this.extractExpressions(value), this.get('metrics'));
  424. value.computedValue = value.value.replace(this.get('EXPRESSION_REGEX'), function (match) {
  425. var float = parseFloat(computeExpression[match]);
  426. if (isNaN(float)) {
  427. return computeExpression[match] || "<span class=\"grey\">n/a</span>";
  428. } else {
  429. return String((float % 1 !== 0) ? float.toFixed(2) : float);
  430. }
  431. });
  432. }, this);
  433. },
  434. /**
  435. * extract expressions
  436. * Example:
  437. * input: "${a/b} equal ${b+a}"
  438. * expressions: ['a/b', 'b+a']
  439. *
  440. * @param {object} input
  441. * @returns {Array}
  442. */
  443. extractExpressions: function (input) {
  444. var pattern = this.get('EXPRESSION_REGEX'),
  445. expressions = [],
  446. match;
  447. if (Em.isNone(input)) return expressions;
  448. while (match = pattern.exec(input.value)) {
  449. expressions.push(match[1]);
  450. }
  451. return expressions;
  452. },
  453. /**
  454. * compute expression
  455. * @param expressions
  456. * @param metrics
  457. * @returns {object}
  458. */
  459. computeExpression: function (expressions, metrics) {
  460. var result = {};
  461. expressions.forEach(function (_expression) {
  462. var validExpression = true;
  463. var value = "";
  464. //replace values with metrics data
  465. var beforeCompute = _expression.replace(this.get('VALUE_NAME_REGEX'), function (match) {
  466. if (window.isNaN(match)) {
  467. if (metrics.someProperty('name', match)) {
  468. return metrics.findProperty('name', match).data;
  469. } else {
  470. validExpression = false;
  471. }
  472. } else {
  473. return match;
  474. }
  475. });
  476. //check for correct math expression
  477. if (!(validExpression && this.get('MATH_EXPRESSION_REGEX').test(beforeCompute))) {
  478. validExpression = false;
  479. }
  480. result['${' + _expression + '}'] = (validExpression) ? Number(window.eval(beforeCompute)).toString() : value;
  481. }, this);
  482. return result;
  483. },
  484. /*
  485. * make call when clicking on "remove icon" on widget
  486. */
  487. hideWidget: function (event) {
  488. this.get('controller').hideWidget(
  489. {
  490. context: Em.Object.create({
  491. id: event.context
  492. })
  493. }
  494. );
  495. },
  496. /*
  497. * make call when clicking on "clone icon" on widget
  498. */
  499. cloneWidget: function (event) {
  500. var self = this;
  501. return App.showConfirmationPopup(
  502. function () {
  503. self.postWidgetDefinition(true);
  504. },
  505. Em.I18n.t('widget.clone.body').format(stringUtils.htmlEntities(self.get('content.widgetName'))),
  506. null,
  507. null,
  508. Em.I18n.t('common.clone')
  509. );
  510. },
  511. /**
  512. * collect all needed data to create new widget
  513. * @returns {{WidgetInfo: {widget_name: *, widget_type: *, description: *, scope: *, metrics: *, values: *, properties: *}}}
  514. */
  515. collectWidgetData: function () {
  516. return {
  517. WidgetInfo: {
  518. widget_name: this.get('content.widgetName'),
  519. widget_type: this.get('content.widgetType'),
  520. description: this.get('content.widgetDescription'),
  521. scope: this.get('content.scope'),
  522. "metrics": this.get('content.metrics').map(function (metric) {
  523. return {
  524. "name": metric.name,
  525. "service_name": metric.service_name,
  526. "component_name": metric.component_name,
  527. "host_component_criteria": metric.host_component_criteria,
  528. "metric_path": metric.metric_path
  529. }
  530. }),
  531. values: this.get('content.values'),
  532. properties: this.get('content.properties')
  533. }
  534. };
  535. },
  536. /**
  537. * post widget definition to server
  538. * @param {boolean} isClone
  539. * * @param {boolean} isEditClonedWidget
  540. * @returns {$.ajax}
  541. */
  542. postWidgetDefinition: function (isClone, isEditClonedWidget) {
  543. var data = this.collectWidgetData();
  544. if (isClone) {
  545. data.WidgetInfo.widget_name += this.get('CLONE_SUFFIX');
  546. data.WidgetInfo.scope = 'USER';
  547. }
  548. var successCallback = isEditClonedWidget ? 'editNewClonedWidget' : 'postWidgetDefinitionSuccessCallback';
  549. return App.ajax.send({
  550. name: 'widgets.wizard.add',
  551. sender: this,
  552. data: {
  553. data: data
  554. },
  555. success: successCallback
  556. });
  557. },
  558. postWidgetDefinitionSuccessCallback: function (data) {
  559. var widgets = this.get('content.layout.widgets').toArray();
  560. widgets.pushObject(Em.Object.create({
  561. id: data.resources[0].WidgetInfo.id
  562. }));
  563. var mainServiceInfoSummaryController = App.router.get('mainServiceInfoSummaryController');
  564. mainServiceInfoSummaryController.saveWidgetLayout(widgets).done(function(){
  565. mainServiceInfoSummaryController.updateActiveLayout();
  566. });
  567. },
  568. /*
  569. * enter edit wizard of the newly cloned widget
  570. */
  571. editNewClonedWidget: function (data) {
  572. var controller = this.get('controller');
  573. var widgets = this.get('content.layout.widgets').toArray();
  574. var id = data.resources[0].WidgetInfo.id;
  575. widgets.pushObject(Em.Object.create({
  576. id: id
  577. }));
  578. var mainServiceInfoSummaryController = App.router.get('mainServiceInfoSummaryController');
  579. mainServiceInfoSummaryController.saveWidgetLayout(widgets).done(function() {
  580. mainServiceInfoSummaryController.getActiveWidgetLayout().done(function() {
  581. var newWidget = App.Widget.find().findProperty('id', id);
  582. controller.editWidget(newWidget);
  583. });
  584. });
  585. },
  586. /*
  587. * make call when clicking on "edit icon" on widget
  588. */
  589. editWidget: function (event) {
  590. var self = this;
  591. var isShared = this.get('content.scope') == 'CLUSTER';
  592. if (!isShared) {
  593. self.get('controller').editWidget(self.get('content'));
  594. } else {
  595. return App.ModalPopup.show({
  596. header: Em.I18n.t('common.warning'),
  597. bodyClass: Em.View.extend({
  598. template: Ember.Handlebars.compile('{{t widget.edit.body}}')
  599. }),
  600. primary: Em.I18n.t('widget.edit.button.primary'),
  601. secondary: Em.I18n.t('widget.edit.button.secondary'),
  602. third: Em.I18n.t('common.cancel'),
  603. onPrimary: function () {
  604. this.hide();
  605. self.get('controller').editWidget(self.get('content'));
  606. },
  607. onSecondary: function () {
  608. this.hide();
  609. self.postWidgetDefinition(true, true);
  610. },
  611. onThird: function () {
  612. this.hide();
  613. }
  614. });
  615. }
  616. }
  617. });
  618. App.WidgetPreviewMixin = Ember.Mixin.create({
  619. beforeRender: Em.K,
  620. isLoaded: true,
  621. metrics: [],
  622. content: Em.Object.create({
  623. id: 1,
  624. values: []
  625. }),
  626. loadMetrics: function () {
  627. this.get('content').setProperties({
  628. 'values': this.get('controller.widgetValues'),
  629. 'properties': this.get('controller.widgetProperties'),
  630. 'widgetName': this.get('controller.widgetName'),
  631. 'metrics': this.get('controller.widgetMetrics')
  632. });
  633. this._super();
  634. }.observes('controller.widgetProperties', 'controller.widgetValues', 'controller.widgetMetrics', 'controller.widgetName'),
  635. onMetricsLoaded: function () {
  636. this.drawWidget();
  637. }
  638. });
  639. /**
  640. * aggregate requests to load metrics by component name
  641. * requests can be added via add method
  642. * input example:
  643. * {
  644. * data: request,
  645. * context: this,
  646. * startCallName: this.getServiceComponentMetrics,
  647. * successCallback: this.getMetricsSuccessCallback,
  648. * completeCallback: function () {
  649. * requestCounter--;
  650. * if (requestCounter === 0) this.onMetricsLoaded();
  651. * }
  652. * }
  653. * @type {Em.Object}
  654. */
  655. App.WidgetLoadAggregator = Em.Object.create({
  656. /**
  657. * @type {Array}
  658. */
  659. requests: [],
  660. /**
  661. * @type {number|null}
  662. */
  663. timeoutId: null,
  664. /**
  665. * @type {number}
  666. * @const
  667. */
  668. BULK_INTERVAL: 1000,
  669. arrayUtils: require('utils/array_utils'),
  670. /**
  671. * add request
  672. * every {{BULK_INTERVAL}} requests get collected, aggregated and sent to server
  673. *
  674. * @param {object} request
  675. */
  676. add: function (request) {
  677. var self = this;
  678. this.get('requests').push(request);
  679. if (Em.isNone(this.get('timeoutId'))) {
  680. this.set('timeoutId', window.setTimeout(function () {
  681. //clear requests that are belongs to destroyed views
  682. self.set('requests', self.get('requests').filterProperty('context.state', 'inDOM'));
  683. self.runRequests(self.get('requests'));
  684. self.get('requests').clear();
  685. clearTimeout(self.get('timeoutId'));
  686. self.set('timeoutId', null);
  687. }, this.get('BULK_INTERVAL')));
  688. }
  689. },
  690. /**
  691. * return requests which grouped into bulks
  692. * @param {Array} requests
  693. * @returns {object} bulks
  694. */
  695. groupRequests: function (requests) {
  696. var bulks = {};
  697. requests.forEach(function (request) {
  698. //poll metrics for graph widgets separately
  699. var graphSuffix = request.context.get('content.widgetType') === "GRAPH" ? "_graph" : '';
  700. var id = request.startCallName + "_" + request.data.component_name + graphSuffix;
  701. if (Em.isNone(bulks[id])) {
  702. bulks[id] = {
  703. data: request.data,
  704. context: request.context,
  705. startCallName: request.startCallName
  706. };
  707. bulks[id].subRequests = [{
  708. context: request.context,
  709. successCallback: request.successCallback,
  710. errorCallback: request.errorCallback,
  711. completeCallback: request.completeCallback
  712. }];
  713. } else {
  714. bulks[id].data.metric_paths.pushObjects(request.data.metric_paths);
  715. bulks[id].subRequests.push({
  716. context: request.context,
  717. successCallback: request.successCallback,
  718. errorCallback: request.errorCallback,
  719. completeCallback: request.completeCallback
  720. });
  721. }
  722. }, this);
  723. return bulks;
  724. },
  725. /**
  726. * run aggregated requests
  727. * @param {Array} requests
  728. */
  729. runRequests: function (requests) {
  730. var bulks = this.groupRequests(requests);
  731. var self = this;
  732. for (var id in bulks) {
  733. (function (_request) {
  734. _request.data.metric_paths = self.arrayUtils.uniqObjectsbyId(_request.data.metric_paths, "id");
  735. _request.context[_request.startCallName].call(_request.context, _request.data).done(function (response) {
  736. _request.subRequests.forEach(function (subRequest) {
  737. subRequest.successCallback.call(subRequest.context, response);
  738. }, this);
  739. }).fail(function (xhr, textStatus, errorThrown) {
  740. _request.subRequests.forEach(function (subRequest) {
  741. if (subRequest.errorCallback) {
  742. subRequest.errorCallback.call(subRequest.context, xhr, textStatus, errorThrown);
  743. }
  744. }, this);
  745. }).always(function (xhr) {
  746. _request.subRequests.forEach(function (subRequest) {
  747. subRequest.completeCallback.call(subRequest.context, xhr);
  748. }, this);
  749. });
  750. })(bulks[id]);
  751. }
  752. }
  753. });