widget_mixin.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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\.\,\:\=\[\]]+/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. completeCallback: function () {
  106. requestCounter--;
  107. if (requestCounter === 0) this.onMetricsLoaded();
  108. }
  109. });
  110. } else {
  111. App.WidgetLoadAggregator.add({
  112. data: request,
  113. context: this,
  114. startCallName: 'getServiceComponentMetrics',
  115. successCallback: this.getMetricsSuccessCallback,
  116. completeCallback: function () {
  117. requestCounter--;
  118. if (requestCounter === 0) this.onMetricsLoaded();
  119. }
  120. });
  121. }
  122. }
  123. }.observes('customTimeRange', 'content.properties.time_range'),
  124. /**
  125. * get data formatted for request
  126. * @param {Array} metrics
  127. */
  128. getRequestData: function (metrics) {
  129. var requestsData = {};
  130. if (metrics) {
  131. metrics.forEach(function (metric, index) {
  132. var key;
  133. if (metric.host_component_criteria) {
  134. key = metric.service_name + '_' + metric.component_name + '_' + metric.host_component_criteria;
  135. } else {
  136. key = metric.service_name + '_' + metric.component_name;
  137. }
  138. var requestMetric = $.extend({}, metric);
  139. if (requestsData[key]) {
  140. requestsData[key]["metric_paths"].push({
  141. metric_path: requestMetric["metric_path"],
  142. metric_type: this.get('metricType'),
  143. id: requestMetric["metric_path"] + "_" + this.get('metricType'),
  144. context: this
  145. });
  146. } else {
  147. requestMetric["metric_paths"] = [{
  148. metric_path: requestMetric["metric_path"],
  149. metric_type: this.get('metricType'),
  150. id: requestMetric["metric_path"] + "_" + this.get('metricType'),
  151. context: this}];
  152. delete requestMetric["metric_path"];
  153. requestsData[key] = requestMetric;
  154. }
  155. }, this);
  156. }
  157. return requestsData;
  158. },
  159. /**
  160. * Tweak host component criteria from the actual host component criteria
  161. * @param {object} request
  162. */
  163. computeHostComponentCriteria: function (request) {
  164. return request.host_component_criteria.replace('host_components/', '&').trim();
  165. },
  166. /**
  167. * make GET call to server in order to fetch service-component metrics
  168. * @param {object} request
  169. * @returns {$.ajax}
  170. */
  171. getServiceComponentMetrics: function (request) {
  172. return App.ajax.send({
  173. name: 'widgets.serviceComponent.metrics.get',
  174. sender: this,
  175. data: {
  176. serviceName: request.service_name,
  177. componentName: request.component_name,
  178. metricPaths: this.prepareMetricPaths(request.metric_paths)
  179. }
  180. });
  181. },
  182. /**
  183. * aggregate all metric names in the query. Add time range and step to temporal queries
  184. */
  185. prepareMetricPaths: function(metricPaths) {
  186. var temporalMetrics = metricPaths.filterProperty('metric_type', 'TEMPORAL');
  187. var pointInTimeMetrics = metricPaths.filterProperty('metric_type', 'POINT_IN_TIME');
  188. var result = temporalMetrics.length ? temporalMetrics[0].context.addTimeProperties(temporalMetrics.mapProperty('metric_path')) : [];
  189. if (pointInTimeMetrics.length) {
  190. result = result.concat(pointInTimeMetrics.mapProperty('metric_path'));
  191. }
  192. return result.join(',');
  193. },
  194. /**
  195. * make GET call to server in order to fetch specific host-component metrics
  196. * @param {object} request
  197. * @returns {$.ajax}
  198. */
  199. getHostComponentMetrics: function (request) {
  200. return App.ajax.send({
  201. name: 'widgets.hostComponent.metrics.get',
  202. sender: this,
  203. data: {
  204. componentName: request.component_name,
  205. metricPaths: this.prepareMetricPaths(request.metric_paths),
  206. hostComponentCriteria: this.computeHostComponentCriteria(request)
  207. }
  208. });
  209. },
  210. getHostComponentMetricsSuccessCallback: function (data) {
  211. if (data.items[0]) {
  212. this.getMetricsSuccessCallback(data.items[0]);
  213. }
  214. },
  215. /**
  216. * callback on getting aggregated metrics and host component metrics
  217. * @param data
  218. */
  219. getMetricsSuccessCallback: function (data) {
  220. var metrics = [];
  221. if (this.get('content.metrics')) {
  222. this.get('content.metrics').forEach(function (_metric) {
  223. var metric_path = _metric.metric_path;
  224. var isAggregatorFunc = false;
  225. var metric_data = Em.get(data, metric_path.replace(/\//g, '.'));
  226. if (Em.isNone(metric_data)) {
  227. this.aggregatorFunc.forEach(function (_item) {
  228. if (metric_path.endsWith(_item) && !isAggregatorFunc) {
  229. isAggregatorFunc = true;
  230. var metricBeanProperty = metric_path.split("/").pop();
  231. var metricBean;
  232. metric_path = metric_path.substring(0, metric_path.indexOf(metricBeanProperty));
  233. if (metric_path.endsWith("/")) {
  234. metric_path = metric_path.slice(0, -1);
  235. }
  236. metricBean = Em.get(data, metric_path.replace(/\//g, '.'));
  237. if (!Em.isNone(metricBean)) {
  238. metric_data = metricBean[metricBeanProperty];
  239. }
  240. }
  241. }, this);
  242. }
  243. if (!Em.isNone(metric_data)) {
  244. _metric.data = metric_data;
  245. this.get('metrics').pushObject(_metric);
  246. }
  247. }, this);
  248. }
  249. },
  250. /**
  251. * make GET call to get metrics value for all host components
  252. * @param {object} request
  253. * @return {$.ajax}
  254. */
  255. getHostComponentsMetrics: function (request) {
  256. request.metric_paths.forEach(function (_metric, index) {
  257. request.metric_paths[index] = "host_components/" + _metric.metric_path;
  258. });
  259. return App.ajax.send({
  260. name: 'widgets.serviceComponent.metrics.get',
  261. sender: this,
  262. data: {
  263. serviceName: request.service_name,
  264. componentName: request.component_name,
  265. metricPaths: request.metric_paths.join(',')
  266. },
  267. success: 'getHostComponentsMetricsSuccessCallback'
  268. });
  269. },
  270. getHostComponentsMetricsSuccessCallback: function (data) {
  271. var metrics = this.get('content.metrics');
  272. data.host_components.forEach(function (item) {
  273. metrics.forEach(function (_metric) {
  274. if (!Em.isNone(Em.get(item, _metric.metric_path.replace(/\//g, '.')))) {
  275. var metric = $.extend({}, _metric, true);
  276. metric.data = Em.get(item, _metric.metric_path.replace(/\//g, '.'));
  277. metric.hostName = item.HostRoles.host_name;
  278. this.get('metrics').pushObject(metric);
  279. }
  280. }, this);
  281. }, this);
  282. },
  283. getHostsMetrics: function (request) {
  284. var metricPaths = request.metric_paths.mapProperty('metric_path');
  285. return App.ajax.send({
  286. name: 'widgets.hosts.metrics.get',
  287. sender: this,
  288. data: {
  289. metricPaths: metricPaths.join(',')
  290. },
  291. success: 'getHostsMetricsSuccessCallback'
  292. });
  293. },
  294. getHostsMetricsSuccessCallback: function (data) {
  295. var metrics = this.get('content.metrics');
  296. data.items.forEach(function (item) {
  297. metrics.forEach(function (_metric, index) {
  298. if (!Em.isNone(Em.get(item, _metric.metric_path.replace(/\//g, '.')))) {
  299. var metric = $.extend({}, _metric, true);
  300. metric.data = Em.get(item, _metric.metric_path.replace(/\//g, '.'));
  301. metric.hostName = item.Hosts.host_name;
  302. this.get('metrics').pushObject(metric);
  303. }
  304. }, this);
  305. }, this);
  306. },
  307. /**
  308. * callback on metrics loaded
  309. */
  310. onMetricsLoaded: function () {
  311. var self = this;
  312. if (!this.get('isLoaded')) this.set('isLoaded', true);
  313. this.drawWidget();
  314. clearTimeout(this.get('timeoutId'));
  315. this.set('timeoutId', setTimeout(function () {
  316. self.loadMetrics();
  317. }, App.contentUpdateInterval));
  318. },
  319. /**
  320. * draw widget
  321. */
  322. drawWidget: function () {
  323. if (this.get('isLoaded')) {
  324. this.calculateValues();
  325. this.set('value', (this.get('content.values')[0]) ? this.get('content.values')[0].computedValue : '');
  326. }
  327. },
  328. /**
  329. * initialize tooltips
  330. */
  331. initTooltip: function () {
  332. var self = this;
  333. if (this.get('isLoaded')) {
  334. Em.run.next(function(){
  335. App.tooltip(self.$(".corner-icon > .icon-copy"), {title: Em.I18n.t('common.clone')});
  336. App.tooltip(self.$(".corner-icon > .icon-edit"), {title: Em.I18n.t('common.edit')});
  337. App.tooltip(self.$(".corner-icon > .icon-save"), {title: Em.I18n.t('common.export')});
  338. });
  339. }
  340. }.observes('isLoaded'),
  341. willDestroyElement: function() {
  342. this.$(".corner-icon > .icon-copy").tooltip('destroy');
  343. this.$(".corner-icon > .icon-edit").tooltip('destroy');
  344. this.$(".corner-icon > .icon-save").tooltip('destroy');
  345. },
  346. /**
  347. * calculate series datasets for graph widgets
  348. */
  349. calculateValues: function () {
  350. this.get('content.values').forEach(function (value) {
  351. var computeExpression = this.computeExpression(this.extractExpressions(value), this.get('metrics'));
  352. value.computedValue = value.value.replace(this.get('EXPRESSION_REGEX'), function (match) {
  353. var float = parseFloat(computeExpression[match]);
  354. if (isNaN(float)) {
  355. return computeExpression[match] || "<span class=\"grey\">n/a</span>";
  356. } else {
  357. return String((float % 1 !== 0) ? float.toFixed(2) : float);
  358. }
  359. });
  360. }, this);
  361. },
  362. /**
  363. * extract expressions
  364. * Example:
  365. * input: "${a/b} equal ${b+a}"
  366. * expressions: ['a/b', 'b+a']
  367. *
  368. * @param {object} input
  369. * @returns {Array}
  370. */
  371. extractExpressions: function (input) {
  372. var pattern = this.get('EXPRESSION_REGEX'),
  373. expressions = [],
  374. match;
  375. if (Em.isNone(input)) return expressions;
  376. while (match = pattern.exec(input.value)) {
  377. expressions.push(match[1]);
  378. }
  379. return expressions;
  380. },
  381. /**
  382. * compute expression
  383. * @param expressions
  384. * @param metrics
  385. * @returns {object}
  386. */
  387. computeExpression: function (expressions, metrics) {
  388. var result = {};
  389. expressions.forEach(function (_expression) {
  390. var validExpression = true;
  391. var value = "";
  392. //replace values with metrics data
  393. var beforeCompute = _expression.replace(this.get('VALUE_NAME_REGEX'), function (match) {
  394. if (window.isNaN(match)) {
  395. if (metrics.someProperty('name', match)) {
  396. return metrics.findProperty('name', match).data;
  397. } else {
  398. validExpression = false;
  399. }
  400. } else {
  401. return match;
  402. }
  403. });
  404. //check for correct math expression
  405. if (!(validExpression && this.get('MATH_EXPRESSION_REGEX').test(beforeCompute))) {
  406. validExpression = false;
  407. }
  408. result['${' + _expression + '}'] = (validExpression) ? Number(window.eval(beforeCompute)).toString() : value;
  409. }, this);
  410. return result;
  411. },
  412. /*
  413. * make call when clicking on "remove icon" on widget
  414. */
  415. hideWidget: function (event) {
  416. this.get('controller').hideWidget(
  417. {
  418. context: Em.Object.create({
  419. id: event.context
  420. })
  421. }
  422. );
  423. },
  424. /*
  425. * make call when clicking on "clone icon" on widget
  426. */
  427. cloneWidget: function (event) {
  428. var self = this;
  429. return App.showConfirmationPopup(
  430. function () {
  431. self.postWidgetDefinition(true);
  432. },
  433. Em.I18n.t('widget.clone.body').format(stringUtils.htmlEntities(self.get('content.widgetName'))),
  434. null,
  435. null,
  436. Em.I18n.t('common.clone')
  437. );
  438. },
  439. /**
  440. * collect all needed data to create new widget
  441. * @returns {{WidgetInfo: {widget_name: *, widget_type: *, description: *, scope: *, metrics: *, values: *, properties: *}}}
  442. */
  443. collectWidgetData: function () {
  444. return {
  445. WidgetInfo: {
  446. widget_name: this.get('content.widgetName'),
  447. widget_type: this.get('content.widgetType'),
  448. description: this.get('content.widgetDescription'),
  449. scope: this.get('content.scope'),
  450. "metrics": this.get('content.metrics').map(function (metric) {
  451. return {
  452. "name": metric.name,
  453. "service_name": metric.service_name,
  454. "component_name": metric.component_name,
  455. "host_component_criteria": metric.host_component_criteria,
  456. "metric_path": metric.metric_path
  457. }
  458. }),
  459. values: this.get('content.values'),
  460. properties: this.get('content.properties')
  461. }
  462. };
  463. },
  464. /**
  465. * post widget definition to server
  466. * @param {boolean} isClone
  467. * * @param {boolean} isEditClonedWidget
  468. * @returns {$.ajax}
  469. */
  470. postWidgetDefinition: function (isClone, isEditClonedWidget) {
  471. var data = this.collectWidgetData();
  472. if (isClone) {
  473. data.WidgetInfo.widget_name += this.get('CLONE_SUFFIX');
  474. data.WidgetInfo.scope = 'USER';
  475. }
  476. var successCallback = isEditClonedWidget ? 'editNewClonedWidget' : 'postWidgetDefinitionSuccessCallback';
  477. return App.ajax.send({
  478. name: 'widgets.wizard.add',
  479. sender: this,
  480. data: {
  481. data: data
  482. },
  483. success: successCallback
  484. });
  485. },
  486. postWidgetDefinitionSuccessCallback: function (data) {
  487. var widgets = this.get('content.layout.widgets').toArray();
  488. widgets.pushObject(Em.Object.create({
  489. id: data.resources[0].WidgetInfo.id
  490. }));
  491. var mainServiceInfoSummaryController = App.router.get('mainServiceInfoSummaryController');
  492. mainServiceInfoSummaryController.saveWidgetLayout(widgets).done(function(){
  493. mainServiceInfoSummaryController.updateActiveLayout();
  494. });
  495. },
  496. /*
  497. * enter edit wizard of the newly cloned widget
  498. */
  499. editNewClonedWidget: function (data) {
  500. var controller = this.get('controller');
  501. var widgets = this.get('content.layout.widgets').toArray();
  502. var id = data.resources[0].WidgetInfo.id;
  503. widgets.pushObject(Em.Object.create({
  504. id: id
  505. }));
  506. var mainServiceInfoSummaryController = App.router.get('mainServiceInfoSummaryController');
  507. mainServiceInfoSummaryController.saveWidgetLayout(widgets).done(function() {
  508. mainServiceInfoSummaryController.getActiveWidgetLayout().done(function() {
  509. var newWidget = App.Widget.find().findProperty('id', id);
  510. controller.editWidget(newWidget);
  511. });
  512. });
  513. },
  514. /*
  515. * make call when clicking on "edit icon" on widget
  516. */
  517. editWidget: function (event) {
  518. var self = this;
  519. var isShared = this.get('content.scope') == 'CLUSTER';
  520. if (!isShared) {
  521. self.get('controller').editWidget(self.get('content'));
  522. } else {
  523. return App.ModalPopup.show({
  524. header: Em.I18n.t('common.warning'),
  525. bodyClass: Em.View.extend({
  526. template: Ember.Handlebars.compile('{{t widget.edit.body}}')
  527. }),
  528. primary: Em.I18n.t('widget.edit.button.primary'),
  529. secondary: Em.I18n.t('widget.edit.button.secondary'),
  530. third: Em.I18n.t('common.cancel'),
  531. onPrimary: function () {
  532. this.hide();
  533. self.get('controller').editWidget(self.get('content'));
  534. },
  535. onSecondary: function () {
  536. this.hide();
  537. self.postWidgetDefinition(true, true);
  538. },
  539. onThird: function () {
  540. this.hide();
  541. }
  542. });
  543. }
  544. }
  545. });
  546. App.WidgetPreviewMixin = Ember.Mixin.create({
  547. beforeRender: Em.K,
  548. isLoaded: true,
  549. metrics: [],
  550. content: Em.Object.create({
  551. id: 1,
  552. values: []
  553. }),
  554. loadMetrics: function () {
  555. this.get('content').setProperties({
  556. 'values': this.get('controller.widgetValues'),
  557. 'properties': this.get('controller.widgetProperties'),
  558. 'widgetName': this.get('controller.widgetName'),
  559. 'metrics': this.get('controller.widgetMetrics')
  560. });
  561. this._super();
  562. }.observes('controller.widgetProperties', 'controller.widgetValues', 'controller.widgetMetrics', 'controller.widgetName'),
  563. onMetricsLoaded: function () {
  564. this.drawWidget();
  565. }
  566. });
  567. /**
  568. * aggregate requests to load metrics by component name
  569. * requests can be added via add method
  570. * input example:
  571. * {
  572. * data: request,
  573. * context: this,
  574. * startCallName: this.getServiceComponentMetrics,
  575. * successCallback: this.getMetricsSuccessCallback,
  576. * completeCallback: function () {
  577. * requestCounter--;
  578. * if (requestCounter === 0) this.onMetricsLoaded();
  579. * }
  580. * }
  581. * @type {Em.Object}
  582. */
  583. App.WidgetLoadAggregator = Em.Object.create({
  584. /**
  585. * @type {Array}
  586. */
  587. requests: [],
  588. /**
  589. * @type {number|null}
  590. */
  591. timeoutId: null,
  592. /**
  593. * @type {number}
  594. * @const
  595. */
  596. BULK_INTERVAL: 1000,
  597. arrayUtils: require('utils/array_utils'),
  598. /**
  599. * add request
  600. * every {{BULK_INTERVAL}} requests get collected, aggregated and sent to server
  601. *
  602. * @param {object} request
  603. */
  604. add: function (request) {
  605. var self = this;
  606. this.get('requests').push(request);
  607. if (Em.isNone(this.get('timeoutId'))) {
  608. this.set('timeoutId', window.setTimeout(function () {
  609. //clear requests that are belongs to destroyed views
  610. self.set('requests', self.get('requests').filterProperty('context.state', 'inDOM'));
  611. self.runRequests(self.get('requests'));
  612. self.get('requests').clear();
  613. clearTimeout(self.get('timeoutId'));
  614. self.set('timeoutId', null);
  615. }, this.get('BULK_INTERVAL')));
  616. }
  617. },
  618. /**
  619. * return requests which grouped into bulks
  620. * @param {Array} requests
  621. * @returns {object} bulks
  622. */
  623. groupRequests: function (requests) {
  624. var bulks = {};
  625. requests.forEach(function (request) {
  626. //poll metrics for graph widgets separately
  627. var graphSuffix = request.context.get('content.widgetType') === "GRAPH" ? "_graph" : '';
  628. var id = request.startCallName + "_" + request.data.component_name + graphSuffix;
  629. if (Em.isNone(bulks[id])) {
  630. bulks[id] = {
  631. data: request.data,
  632. context: request.context,
  633. startCallName: request.startCallName
  634. };
  635. bulks[id].subRequests = [{
  636. context: request.context,
  637. successCallback: request.successCallback,
  638. completeCallback: request.completeCallback
  639. }];
  640. } else {
  641. bulks[id].data.metric_paths.pushObjects(request.data.metric_paths);
  642. bulks[id].subRequests.push({
  643. context: request.context,
  644. successCallback: request.successCallback,
  645. completeCallback: request.completeCallback
  646. });
  647. }
  648. }, this);
  649. return bulks;
  650. },
  651. /**
  652. * run aggregated requests
  653. * @param {Array} requests
  654. */
  655. runRequests: function (requests) {
  656. var bulks = this.groupRequests(requests);
  657. var self = this;
  658. for (var id in bulks) {
  659. (function (_request) {
  660. _request.data.metric_paths = self.arrayUtils.uniqObjectsbyId(_request.data.metric_paths, "id");
  661. _request.context[_request.startCallName].call(_request.context, _request.data).done(function (response) {
  662. _request.subRequests.forEach(function (subRequest) {
  663. subRequest.successCallback.call(subRequest.context, response);
  664. }, this);
  665. }).complete(function () {
  666. _request.subRequests.forEach(function (subRequest) {
  667. subRequest.completeCallback.call(subRequest.context);
  668. }, this);
  669. });
  670. })(bulks[id]);
  671. }
  672. }
  673. });