linear_time.js 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with this
  4. * work for additional information regarding copyright ownership. The ASF
  5. * licenses this file to you under the Apache License, Version 2.0 (the
  6. * "License"); you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. * License for the specific language governing permissions and limitations under
  15. * the License.
  16. */
  17. var App = require('app');
  18. var string_utils = require('utils/string_utils');
  19. var dateUtils = require('utils/date/date');
  20. /**
  21. * @class
  22. *
  23. * This is a view which GETs data from a URL and shows it as a time based line
  24. * graph. Time is shown on the X axis with data series shown on Y axis. It
  25. * optionally also has the ability to auto refresh itself over a given time
  26. * interval.
  27. *
  28. * This is an abstract class which is meant to be extended.
  29. *
  30. * Extending classes should override the following:
  31. * <ul>
  32. * <li>url - from where the data can be retrieved
  33. * <li>title - Title to be displayed when showing the chart
  34. * <li>id - which uniquely identifies this chart in any page
  35. * <li>seriesTemplate - template used by getData method to process server data
  36. * </ul>
  37. *
  38. * Extending classes could optionally override the following:
  39. * <ul>
  40. * <li>#getData(jsonData) - function to map server data into series format
  41. * ready for export to graph and JSON formats
  42. * <li>#colorForSeries(series) - function to get custom colors per series
  43. * </ul>
  44. *
  45. * @extends Ember.Object
  46. * @extends Ember.View
  47. */
  48. App.ChartLinearTimeView = Ember.View.extend(App.ExportMetricsMixin, {
  49. templateName: require('templates/main/charts/linear_time'),
  50. /**
  51. * The URL from which data can be retrieved.
  52. *
  53. * This property must be provided for the graph to show properly.
  54. *
  55. * @type String
  56. * @default null
  57. */
  58. url: null,
  59. /**
  60. * A unique ID for this chart.
  61. *
  62. * @type String
  63. * @default null
  64. */
  65. id: null,
  66. /**
  67. * Title to be shown under the chart.
  68. *
  69. * @type String
  70. * @default null
  71. */
  72. title: null,
  73. /**
  74. * @private
  75. *
  76. * @type Rickshaw.Graph
  77. * @default null
  78. */
  79. _graph: null,
  80. /**
  81. * Array of classnames for each series (in widget)
  82. * @type Rickshaw.Graph
  83. */
  84. _popupGraph: null,
  85. /**
  86. * Array of classnames for each series
  87. * @type Array
  88. */
  89. _seriesProperties: null,
  90. /**
  91. * Array of classnames for each series (in widget)
  92. * @type Array
  93. */
  94. _seriesPropertiesWidget: null,
  95. /**
  96. * Renderer type
  97. * See <code>Rickshaw.Graph.Renderer</code> for more info
  98. * @type String
  99. */
  100. renderer: 'area',
  101. /**
  102. * Suffix used in DOM-elements selectors
  103. * @type String
  104. */
  105. popupSuffix: '-popup',
  106. /**
  107. * Is popup for current graph open
  108. * @type Boolean
  109. */
  110. isPopup: false,
  111. /**
  112. * Is graph ready
  113. * @type Boolean
  114. */
  115. isReady: false,
  116. /**
  117. * Is popup-graph ready
  118. * @type Boolean
  119. */
  120. isPopupReady: false,
  121. /**
  122. * Is data for graph available
  123. * @type Boolean
  124. */
  125. hasData: true,
  126. /**
  127. * chart height
  128. * @type {number}
  129. * @default 150
  130. */
  131. height: 150,
  132. /**
  133. * @type {string}
  134. * @default null
  135. */
  136. displayUnit: null,
  137. /**
  138. * Object containing information to get metrics data from API response
  139. * Supported properties:
  140. * <ul>
  141. * <li>path - exact path to metrics data in response JSON (required)
  142. * <li>displayName(name, hostName) - returns display name for metrics
  143. * depending on property name in response JSON and host name for Flume Agents
  144. * <li>factor - number that metrics values should be multiplied by
  145. * <li>flumePropertyName - property name to access certain Flume metrics
  146. * </ul>
  147. * @type {Object}
  148. */
  149. seriesTemplate: null,
  150. _containerSelector: Em.computed.format('#{0}-container', 'id'),
  151. _popupSelector: Em.computed.concat('', '_containerSelector', 'popupSuffix'),
  152. didInsertElement: function () {
  153. var self = this;
  154. this.setYAxisFormatter();
  155. this.loadData();
  156. this.registerGraph();
  157. this.$().parent().on('mouseleave', function () {
  158. self.set('isExportMenuHidden', true);
  159. });
  160. App.tooltip(this.$("[rel='ZoomInTooltip']"), {
  161. placement: 'left',
  162. template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner graph-tooltip"></div></div>'
  163. });
  164. },
  165. /**
  166. * Maps server data into series format ready for export to graph and JSON formats
  167. * @param jsonData
  168. * @returns {Array}
  169. */
  170. getData: function (jsonData) {
  171. var dataArray = [],
  172. template = this.get('seriesTemplate'),
  173. data = Em.get(jsonData, template.path);
  174. if (data) {
  175. for (var name in data) {
  176. var currentData = data[name];
  177. if (currentData) {
  178. var factor = template.factor,
  179. displayName = template.displayName ? template.displayName(name) : name;
  180. if (!Em.isNone(factor)) {
  181. var dataLength = currentData.length;
  182. for (var i = dataLength; i--;) {
  183. currentData[i][0] *= factor;
  184. }
  185. }
  186. dataArray.push({
  187. name: displayName,
  188. data: currentData
  189. });
  190. }
  191. }
  192. }
  193. return dataArray;
  194. },
  195. /**
  196. * Maps server data for certain Flume metrics into series format ready for export
  197. * to graph and JSON formats
  198. * @param jsonData
  199. * @returns {Array}
  200. */
  201. getFlumeData: function (jsonData) {
  202. var dataArray = [];
  203. if (jsonData && jsonData.host_components) {
  204. jsonData.host_components.forEach(function (hc) {
  205. var hostName = hc.HostRoles.host_name,
  206. host = App.Host.find(hostName),
  207. template = this.get('template'),
  208. data = Em.get(hc, template.path);
  209. if (host && host.get('publicHostName')) {
  210. hostName = host.get('publicHostName');
  211. }
  212. if (data) {
  213. for (var cname in data) {
  214. var seriesName = template.displayName ? template.displayName(cname, hostName) : cname,
  215. seriesData = template.flumePropertyName ? data[cname][template.flumePropertyName] : data[cname];
  216. if (seriesData) {
  217. var factor = template.factor;
  218. if (!Em.isNone(factor)) {
  219. var dataLength = seriesData.length;
  220. for (var i = dataLength; i--;) {
  221. seriesData[i][0] *= factor;
  222. }
  223. }
  224. dataArray.push({
  225. name: seriesName,
  226. data: seriesData
  227. });
  228. }
  229. }
  230. }
  231. }, this);
  232. }
  233. return dataArray;
  234. },
  235. /**
  236. * Maps server data for Kafka Broker Topic and Controller Status metrics
  237. * into series format ready for export to graph and JSON formats
  238. * @param jsonData
  239. * @returns {Array}
  240. */
  241. getKafkaData: function (jsonData) {
  242. var dataArray = [],
  243. template = this.get('seriesTemplate'),
  244. data = Em.get(jsonData, template.path);
  245. for (var name in data) {
  246. var displayName = template.displayName(name);
  247. dataArray.push({
  248. name: displayName,
  249. data: Em.get(data, name + '.1MinuteRate')
  250. });
  251. }
  252. return dataArray;
  253. },
  254. /**
  255. * Function to map data into graph series
  256. * @param jsonData
  257. * @returns {Array}
  258. */
  259. transformToSeries: function (jsonData) {
  260. var seriesArray = [],
  261. seriesData = this.getData(jsonData),
  262. dataLength = seriesData.length;
  263. for (var i = 0; i < dataLength; i++) {
  264. seriesArray.push(this.transformData(seriesData[i].data, seriesData[i].name));
  265. }
  266. return seriesArray;
  267. },
  268. setExportTooltip: function () {
  269. if (this.get('isReady')) {
  270. Em.run.next(this, function () {
  271. var icon = this.$('.corner-icon');
  272. if (icon) {
  273. icon.on('mouseover', function () {
  274. $(this).closest("[rel='ZoomInTooltip']").trigger('mouseleave');
  275. });
  276. App.tooltip(icon.children('.icon-save'), {
  277. title: Em.I18n.t('common.export')
  278. });
  279. }
  280. });
  281. }
  282. }.observes('isReady'),
  283. willDestroyElement: function () {
  284. this.$("[rel='ZoomInTooltip']").tooltip('destroy');
  285. $(this.get('_containerSelector') + ' li.line').off();
  286. $(this.get('_popupSelector') + ' li.line').off();
  287. },
  288. registerGraph: function () {
  289. var graph = {
  290. name: this.get('title'),
  291. id: this.get('elementId'),
  292. popupId: this.get('id')
  293. };
  294. App.router.get('updateController.graphs').push(graph);
  295. },
  296. loadData: function () {
  297. if (this.get('loadGroup') && !this.get('isPopup')) {
  298. return App.ChartLinearTimeView.LoadAggregator.add(this, this.get('loadGroup'));
  299. } else {
  300. return App.ajax.send({
  301. name: this.get('ajaxIndex'),
  302. sender: this,
  303. data: this.getDataForAjaxRequest(),
  304. success: 'loadDataSuccessCallback',
  305. error: 'loadDataErrorCallback'
  306. });
  307. }
  308. },
  309. getDataForAjaxRequest: function () {
  310. var toSeconds = Math.round(App.dateTime() / 1000);
  311. var hostName = (this.get('content')) ? this.get('content.hostName') : "";
  312. var HDFSService = App.HDFSService.find().objectAt(0);
  313. var nameNodeName = "";
  314. var YARNService = App.YARNService.find().objectAt(0);
  315. var resourceManager = YARNService ? YARNService.get('resourceManager.hostName') : "";
  316. var timeUnit = this.get('timeUnitSeconds');
  317. if (HDFSService) {
  318. nameNodeName = (HDFSService.get('activeNameNode')) ? HDFSService.get('activeNameNode.hostName') : HDFSService.get('nameNode.hostName');
  319. }
  320. return {
  321. toSeconds: toSeconds,
  322. fromSeconds: toSeconds - timeUnit,
  323. stepSeconds: 15,
  324. hostName: hostName,
  325. nameNodeName: nameNodeName,
  326. resourceManager: resourceManager
  327. };
  328. },
  329. loadDataSuccessCallback: function (response) {
  330. this._refreshGraph(response);
  331. },
  332. loadDataErrorCallback: function (xhr, textStatus, errorThrown) {
  333. this.set('isReady', true);
  334. if (xhr.readyState == 4 && xhr.status) {
  335. textStatus = xhr.status + " " + textStatus;
  336. }
  337. this._showMessage('warn', this.t('graphs.error.title'), this.t('graphs.error.message').format(textStatus, errorThrown));
  338. this.setProperties({
  339. hasData: false,
  340. isExportButtonHidden: true
  341. });
  342. },
  343. /**
  344. * Shows a yellow warning message in place of the chart.
  345. *
  346. * @param type Can be any of 'warn', 'error', 'info', 'success'
  347. * @param title Bolded title for the message
  348. * @param message String representing the message
  349. * @param tooltip Tooltip content
  350. * @type: Function
  351. */
  352. _showMessage: function (type, title, message, tooltip) {
  353. var popupSuffix = this.get('isPopup') ? this.get('popupSuffix') : '';
  354. var chartOverlay = '#' + this.get('id');
  355. var chartOverlayId = chartOverlay + '-chart' + popupSuffix;
  356. var chartOverlayY = chartOverlay + '-yaxis' + popupSuffix;
  357. var chartOverlayX = chartOverlay + '-xaxis' + popupSuffix;
  358. var chartOverlayLegend = chartOverlay + '-legend' + popupSuffix;
  359. var chartOverlayTimeline = chartOverlay + '-timeline' + popupSuffix;
  360. var tooltipTitle = tooltip ? tooltip : Em.I18n.t('graphs.tooltip.title');
  361. var chartContent = '';
  362. var typeClass;
  363. switch (type) {
  364. case 'error':
  365. typeClass = 'alert-error';
  366. break;
  367. case 'success':
  368. typeClass = 'alert-success';
  369. break;
  370. case 'info':
  371. typeClass = 'alert-info';
  372. break;
  373. default:
  374. typeClass = '';
  375. break;
  376. }
  377. $(chartOverlayId + ', ' + chartOverlayY + ', ' + chartOverlayX + ', ' + chartOverlayLegend + ', ' + chartOverlayTimeline).html('');
  378. chartContent += '<div class=\"alert ' + typeClass + '\">';
  379. if (title) {
  380. chartContent += '<strong>' + title + '</strong> ';
  381. }
  382. chartContent += message + '</div>';
  383. $(chartOverlayId).append(chartContent);
  384. $(chartOverlayId).parent().attr('data-original-title', tooltipTitle);
  385. },
  386. /**
  387. * Transforms the JSON data retrieved from the server into the series
  388. * format that Rickshaw.Graph understands.
  389. *
  390. * The series object is generally in the following format: [ { name :
  391. * "Series 1", data : [ { x : 0, y : 0 }, { x : 1, y : 1 } ] } ]
  392. *
  393. * Extending classes should override this method.
  394. *
  395. * @param seriesData
  396. * Data retrieved from the server
  397. * @param displayName
  398. * Graph title
  399. * @type: Function
  400. *
  401. */
  402. transformData: function (seriesData, displayName) {
  403. if (!Em.isNone(seriesData)) {
  404. // Is it a string?
  405. if ("string" == typeof seriesData) {
  406. seriesData = JSON.parse(seriesData);
  407. }
  408. // Is it a number?
  409. if ("number" == typeof seriesData) {
  410. // Same number applies to all time.
  411. var number = seriesData;
  412. seriesData = [];
  413. seriesData.push([number, App.dateTime() - (60 * 60)]);
  414. seriesData.push([number, App.dateTime()]);
  415. }
  416. // We have valid data
  417. var series = {};
  418. series.name = displayName;
  419. series.data = [];
  420. var timeDiff = App.dateTimeWithTimeZone(seriesData[0][1] * 1000) / 1000 - seriesData[0][1];
  421. for (var index = 0; index < seriesData.length; index++) {
  422. series.data.push({
  423. x: seriesData[index][1] + timeDiff,
  424. y: seriesData[index][0]
  425. });
  426. }
  427. return series;
  428. }
  429. return null;
  430. },
  431. /**
  432. * Provides the formatter to use in displaying Y axis.
  433. *
  434. * By default, uses the App.ChartLinearTimeView.DefaultFormatter which shows 10K,
  435. * 300M etc.
  436. *
  437. * @type Function
  438. */
  439. yAxisFormatter: function (y) {
  440. return App.ChartLinearTimeView.DefaultFormatter(y);
  441. },
  442. /**
  443. * Sets the formatter to use in displaying Y axis depending on graph unit.
  444. *
  445. * @type Function
  446. */
  447. setYAxisFormatter: function () {
  448. var method,
  449. formatterMap = {
  450. '%': 'PercentageFormatter',
  451. '/s': 'CreateRateFormatter',
  452. 'B': 'BytesFormatter',
  453. 'ms': 'TimeElapsedFormatter'
  454. },
  455. methodName = formatterMap[this.get('displayUnit')];
  456. if (methodName) {
  457. method = (methodName == 'CreateRateFormatter') ?
  458. App.ChartLinearTimeView.CreateRateFormatter('', App.ChartLinearTimeView.DefaultFormatter) :
  459. App.ChartLinearTimeView[methodName];
  460. this.set('yAxisFormatter', method);
  461. }
  462. },
  463. /**
  464. * Provides the color (in any HTML color format) to use for a particular
  465. * series.
  466. * May be redefined in child views
  467. *
  468. * @param series
  469. * Series for which color is being requested
  470. * @return color String. Returning null allows this chart to pick a color
  471. * from palette.
  472. * @default null
  473. * @type Function
  474. */
  475. colorForSeries: function (series) {
  476. return null;
  477. },
  478. /**
  479. * Check whether seriesData is correct data for chart drawing
  480. * @param {Array} seriesData
  481. * @return {Boolean}
  482. */
  483. checkSeries: function (seriesData) {
  484. if (!seriesData || !seriesData.length) {
  485. return false;
  486. }
  487. var result = true;
  488. seriesData.forEach(function (item) {
  489. if (Em.isNone(Em.get(item, 'data.0.x'))) {
  490. result = false;
  491. }
  492. });
  493. return result;
  494. },
  495. /**
  496. * @private
  497. *
  498. * Refreshes the graph with the latest JSON data.
  499. *
  500. * @type Function
  501. */
  502. _refreshGraph: function (jsonData, graphView) {
  503. if (this.get('isDestroyed')) {
  504. return;
  505. }
  506. console.time('_refreshGraph');
  507. var seriesData = this.transformToSeries(jsonData);
  508. //if graph opened as modal popup
  509. var popup_path = $(this.get('_popupSelector'));
  510. var graph_container = $(this.get('_containerSelector'));
  511. var container;
  512. if (popup_path.length) {
  513. popup_path.children().each(function () {
  514. $(this).children().remove();
  515. });
  516. this.set('isPopup', true);
  517. }
  518. else {
  519. graph_container.children().each(function () {
  520. if (!($(this).is('.export-graph-list-container, .corner-icon'))) {
  521. $(this).children().remove();
  522. }
  523. });
  524. }
  525. var hasData = this.checkSeries(seriesData);
  526. var view = graphView || this;
  527. view.set('isExportButtonHidden', !hasData);
  528. if (hasData) {
  529. // Check container exists (may be not, if we go to another page and wait while graphs loading)
  530. if (graph_container.length) {
  531. container = $(this.get('_containerSelector'));
  532. this.draw(seriesData);
  533. this.set('hasData', true);
  534. //move yAxis value lower to make them fully visible
  535. container.find('.y_axis text').attr('y', 8);
  536. container.attr('data-original-title', Em.I18n.t('graphs.tooltip.title'));
  537. }
  538. }
  539. else {
  540. this.set('isReady', true);
  541. //if Axis X time interval is default(60 minutes)
  542. if (this.get('timeUnitSeconds') === 3600) {
  543. this._showMessage('info', null, this.t('graphs.noData.message'), this.t('graphs.noData.tooltip.title'));
  544. this.set('hasData', false);
  545. }
  546. else {
  547. this._showMessage('info', this.t('graphs.noData.title'), this.t('graphs.noDataAtTime.message'));
  548. }
  549. }
  550. graph_container = null;
  551. container = null;
  552. popup_path = null;
  553. console.timeEnd('_refreshGraph');
  554. },
  555. /**
  556. * Returns a custom time unit, that depends on X axis interval length, for the graph's X axis.
  557. * This is needed as Rickshaw's default time X axis uses UTC time, which can be confusing
  558. * for users expecting locale specific time.
  559. *
  560. * If <code>null</code> is returned, Rickshaw's default time unit is used.
  561. *
  562. * @type Function
  563. * @return Rickshaw.Fixtures.Time
  564. */
  565. localeTimeUnit: function (timeUnitSeconds) {
  566. var timeUnit = new Rickshaw.Fixtures.Time();
  567. switch (timeUnitSeconds) {
  568. case 604800:
  569. timeUnit = timeUnit.unit('day');
  570. break;
  571. case 2592000:
  572. timeUnit = timeUnit.unit('week');
  573. break;
  574. case 31104000:
  575. timeUnit = timeUnit.unit('month');
  576. break;
  577. default:
  578. timeUnit = {
  579. name: timeUnitSeconds / 240 + ' minute',
  580. seconds: timeUnitSeconds / 4,
  581. formatter: function (d) {
  582. // format locale specific time
  583. var minutes = dateUtils.dateFormatZeroFirst(d.getMinutes());
  584. var hours = dateUtils.dateFormatZeroFirst(d.getHours());
  585. return hours + ":" + minutes;
  586. }
  587. };
  588. }
  589. return timeUnit;
  590. },
  591. /**
  592. * calculate statistic data for popup legend and set proper colors for series
  593. * @param {Array} data
  594. */
  595. dataPreProcess: function (data) {
  596. var self = this;
  597. var palette = new Rickshaw.Color.Palette({scheme: 'munin'});
  598. // Format series for display
  599. var series_min_length = 100000000;
  600. data.forEach(function (series) {
  601. var displayUnit = self.get('displayUnit');
  602. var seriesColor = self.colorForSeries(series);
  603. if (Em.isNone(seriesColor)) {
  604. seriesColor = palette.color();
  605. }
  606. series.color = seriesColor;
  607. series.stroke = 'rgba(0,0,0,0.3)';
  608. // calculate statistic data for popup legend
  609. var avg = 0;
  610. var min = Number.MAX_VALUE;
  611. var max = Number.MIN_VALUE;
  612. var numberOfNotNullValues = 0;
  613. series.isZero = true;
  614. for (var i = 0; i < series.data.length; i++) {
  615. avg += series.data[i]['y'];
  616. if (series.data[i]['y'] !== null) {
  617. numberOfNotNullValues++;
  618. }
  619. if (!Em.isNone(series.data[i]['y'])) {
  620. if (series.data[i]['y'] < min) {
  621. min = series.data[i]['y'];
  622. }
  623. }
  624. if (series.data[i]['y'] > max) {
  625. max = series.data[i]['y'];
  626. }
  627. if (series.data[i]['y'] > 1) {
  628. series.isZero = false;
  629. }
  630. }
  631. if (self.get('isPopup')) {
  632. series.name = string_utils.pad(series.name.length > 36 ? series.name.substr(0, 36) + '...' : series.name, 40, '&nbsp;', 2) + '|&nbsp;' +
  633. string_utils.pad('min', 5, '&nbsp;', 3) +
  634. string_utils.pad(self.get('yAxisFormatter')(min), 12, '&nbsp;', 3) +
  635. string_utils.pad('avg', 5, '&nbsp;', 3) +
  636. string_utils.pad(self.get('yAxisFormatter')(avg / numberOfNotNullValues), 12, '&nbsp;', 3) +
  637. string_utils.pad('max', 12, '&nbsp;', 3) +
  638. string_utils.pad(self.get('yAxisFormatter')(max), 5, '&nbsp;', 3);
  639. }
  640. if (series.isZero) {
  641. series.stroke = series.color;
  642. }
  643. if (series.data.length < series_min_length) {
  644. series_min_length = series.data.length;
  645. }
  646. });
  647. // All series should have equal length
  648. data.forEach(function (series) {
  649. if (series.data.length > series_min_length) {
  650. series.data.length = series_min_length;
  651. }
  652. });
  653. },
  654. draw: function (seriesData) {
  655. var self = this;
  656. var isPopup = this.get('isPopup');
  657. var p = isPopup ? this.get('popupSuffix') : '';
  658. this.dataPreProcess(seriesData);
  659. var chartElement = document.querySelector("#" + this.get('id') + "-chart" + p);
  660. var overlayElement = document.querySelector(+this.get('id') + "-container" + p);
  661. var xaxisElement = document.querySelector("#" + this.get('id') + "-xaxis" + p);
  662. var yaxisElement = document.querySelector("#" + this.get('id') + "-yaxis" + p);
  663. var legendElement = document.querySelector("#" + this.get('id') + "-legend" + p);
  664. var graphSize = this._calculateGraphSize();
  665. var _graph = new Rickshaw.GraphReopened({
  666. height: graphSize.height,
  667. width: graphSize.width,
  668. element: chartElement,
  669. series: seriesData,
  670. interpolation: 'step-after',
  671. stroke: true,
  672. renderer: this.get('renderer'),
  673. strokeWidth: 'area' === this.get('renderer') ? 1 : 2,
  674. max: seriesData.everyProperty('isZero') ? 1 : null
  675. });
  676. if ('area' === this.get('renderer')) {
  677. _graph.renderer.unstack = false;
  678. }
  679. new Rickshaw.Graph.Axis.Time({
  680. graph: _graph,
  681. timeUnit: this.localeTimeUnit(this.get('timeUnitSeconds'))
  682. });
  683. new Rickshaw.Graph.Axis.Y({
  684. tickFormat: this.yAxisFormatter,
  685. pixelsPerTick: isPopup ? 75 : 40,
  686. element: yaxisElement,
  687. orientation: isPopup ? 'left' : 'right',
  688. graph: _graph
  689. });
  690. var legend = new Rickshaw.Graph.Legend({
  691. graph: _graph,
  692. element: legendElement,
  693. description: self.get('description')
  694. });
  695. new Rickshaw.Graph.Behavior.Series.Toggle({
  696. graph: _graph,
  697. legend: legend
  698. });
  699. new Rickshaw.Graph.Behavior.Series.Order({
  700. graph: _graph,
  701. legend: legend
  702. });
  703. if (!isPopup) {
  704. $(overlayElement).on('mousemove', function () {
  705. $(xaxisElement).removeClass('hide');
  706. $(legendElement).removeClass('hide');
  707. $(chartElement).children("div").removeClass('hide');
  708. });
  709. $(overlayElement).on('mouseout', function () {
  710. $(legendElement).addClass('hide');
  711. });
  712. _graph.onUpdate(function () {
  713. $(legendElement).addClass('hide');
  714. });
  715. }
  716. this.$().on('remove', function () {
  717. $(overlayElement).off();
  718. });
  719. //show the graph when it's loaded
  720. _graph.onUpdate(function () {
  721. self.set('isReady', true);
  722. });
  723. _graph.render();
  724. if (isPopup) {
  725. new Rickshaw.Graph.HoverDetail({
  726. graph: _graph,
  727. yFormatter: function (y) {
  728. return self.yAxisFormatter(y);
  729. },
  730. xFormatter: function (x) {
  731. return (new Date(x * 1000)).toLocaleTimeString();
  732. },
  733. formatter: function (series, x, y, formattedX, formattedY) {
  734. return formattedY + '<br />' + formattedX;
  735. }
  736. });
  737. }
  738. _graph = this.updateSeriesInGraph(_graph);
  739. if (isPopup) {
  740. //show the graph when it's loaded
  741. _graph.onUpdate(function () {
  742. self.set('isPopupReady', true);
  743. });
  744. _graph.update();
  745. var popupSelector = this.get('_popupSelector');
  746. $(popupSelector + ' li.line').click(function () {
  747. var series = [];
  748. $(popupSelector + ' a.action').each(function (index, v) {
  749. series[index] = v.parentNode.classList;
  750. });
  751. self.set('_seriesProperties', series);
  752. });
  753. this.set('_popupGraph', _graph);
  754. }
  755. else {
  756. _graph.update();
  757. var containerSelector = this.get('_containerSelector');
  758. $(containerSelector + ' li.line').click(function () {
  759. var series = [];
  760. $(containerSelector + ' a.action').each(function (index, v) {
  761. series[index] = v.parentNode.classList;
  762. });
  763. self.set('_seriesPropertiesWidget', series);
  764. });
  765. this.set('_graph', _graph);
  766. }
  767. },
  768. /**
  769. * Calculate graph size
  770. * @returns {{width: number, height: number}}
  771. * @private
  772. */
  773. _calculateGraphSize: function () {
  774. var isPopup = this.get('isPopup');
  775. var height = this.get('height');
  776. var width = 400;
  777. var diff = 32;
  778. if (this.get('inWidget')) {
  779. height = 105; // for widgets view
  780. diff = 22;
  781. }
  782. if (isPopup) {
  783. height = 180;
  784. width = 670;
  785. }
  786. else {
  787. // If not in popup, the width could vary.
  788. // We determine width based on div's size.
  789. var thisElement = this.get('element');
  790. if (!Em.isNone(thisElement)) {
  791. var calculatedWidth = $(thisElement).width();
  792. if (calculatedWidth > diff) {
  793. width = calculatedWidth - diff;
  794. }
  795. }
  796. }
  797. return {
  798. width: width,
  799. height: height
  800. }
  801. },
  802. /**
  803. *
  804. * @param {Rickshaw.Graph} graph
  805. * @returns {Rickshaw.Graph}
  806. */
  807. updateSeriesInGraph: function (graph) {
  808. var id = this.get('id');
  809. var isPopup = this.get('isPopup');
  810. var popupSuffix = this.get('popupSuffix');
  811. var _series = isPopup ? this.get('_seriesProperties') : this.get('_seriesPropertiesWidget');
  812. graph.series.forEach(function (series, index) {
  813. if (_series && !Em.isNone(_series[index])) {
  814. if (_series[_series.length - index - 1].length > 1) {
  815. var s = '#' + id + '-container' + (isPopup ? popupSuffix : '') + ' a.action:eq(' + (_series.length - index - 1) + ')';
  816. $(s).parent('li').addClass('disabled');
  817. series.disable();
  818. }
  819. }
  820. });
  821. return graph;
  822. },
  823. showGraphInPopup: function () {
  824. if (!this.get('hasData') || this.get('isPreview')) {
  825. return;
  826. }
  827. this.set('isPopup', true);
  828. var self = this;
  829. App.ModalPopup.show({
  830. bodyClass: Em.View.extend(App.ExportMetricsMixin, {
  831. containerId: null,
  832. containerClass: null,
  833. yAxisId: null,
  834. yAxisClass: null,
  835. xAxisId: null,
  836. xAxisClass: null,
  837. legendId: null,
  838. legendClass: null,
  839. chartId: null,
  840. chartClass: null,
  841. titleId: null,
  842. titleClass: null,
  843. isReady: Em.computed.alias('parentView.graph.isPopupReady'),
  844. didInsertElement: function () {
  845. var popupBody = this;
  846. App.tooltip(this.$('.corner-icon > .icon-save'), {
  847. title: Em.I18n.t('common.export')
  848. });
  849. this.$().closest('.modal').on('click', function (event) {
  850. if (!($(event.target).is('.corner-icon, .icon-save, .export-graph-list-container, .export-graph-list-container *'))) {
  851. popupBody.set('isExportMenuHidden', true);
  852. }
  853. });
  854. $('#modal').addClass('modal-graph-line');
  855. var popupSuffix = this.get('parentView.graph.popupSuffix');
  856. var id = this.get('parentView.graph.id');
  857. var idTemplate = id + '-{element}' + popupSuffix;
  858. this.set('containerId', idTemplate.replace('{element}', 'container'));
  859. this.set('containerClass', 'chart-container' + popupSuffix);
  860. this.set('yAxisId', idTemplate.replace('{element}', 'yaxis'));
  861. this.set('yAxisClass', this.get('yAxisId').replace(popupSuffix, ''));
  862. this.set('xAxisId', idTemplate.replace('{element}', 'xaxis'));
  863. this.set('xAxisClass', this.get('xAxisId').replace(popupSuffix, ''));
  864. this.set('legendId', idTemplate.replace('{element}', 'legend'));
  865. this.set('legendClass', this.get('legendId').replace(popupSuffix, ''));
  866. this.set('chartId', idTemplate.replace('{element}', 'chart'));
  867. this.set('chartClass', this.get('chartId').replace(popupSuffix, ''));
  868. this.set('titleId', idTemplate.replace('{element}', 'title'));
  869. this.set('titleClass', this.get('titleId').replace(popupSuffix, ''));
  870. },
  871. templateName: require('templates/common/chart/linear_time'),
  872. /**
  873. * check is time paging feature is enable for graph
  874. */
  875. isTimePagingEnable: function () {
  876. return !self.get('isTimePagingDisable');
  877. }.property(),
  878. rightArrowVisible: function () {
  879. return (this.get('isReady') && (this.get('parentView.currentTimeIndex') != 0));
  880. }.property('isReady', 'parentView.currentTimeIndex'),
  881. leftArrowVisible: function () {
  882. return (this.get('isReady') && (this.get('parentView.currentTimeIndex') != 7));
  883. }.property('isReady', 'parentView.currentTimeIndex'),
  884. exportGraphData: function (event) {
  885. this.set('isExportMenuHidden', true);
  886. var ajaxIndex = this.get('parentView.graph.ajaxIndex'),
  887. targetView = ajaxIndex ? this.get('parentView.graph') : self.get('parentView');
  888. targetView.exportGraphData({
  889. context: event.context
  890. });
  891. }
  892. }),
  893. header: this.get('title'),
  894. /**
  895. * App.ChartLinearTimeView
  896. */
  897. graph: self,
  898. secondary: null,
  899. onPrimary: function () {
  900. self.setProperties({
  901. currentTimeIndex: !Em.isNone(self.get('parentView.currentTimeRangeIndex')) ? self.get('parentView.currentTimeRangeIndex') : self.get('parentView.parentView.currentTimeRangeIndex'),
  902. isPopup: false
  903. });
  904. this._super();
  905. },
  906. onClose: function () {
  907. this.onPrimary();
  908. },
  909. /**
  910. * move graph back by time
  911. * @param event
  912. */
  913. switchTimeBack: function (event) {
  914. var index = this.get('currentTimeIndex');
  915. // 7 - number of last time state
  916. if (index < 7) {
  917. this.reloadGraphByTime(++index);
  918. }
  919. },
  920. /**
  921. * move graph forward by time
  922. * @param event
  923. */
  924. switchTimeForward: function (event) {
  925. var index = this.get('currentTimeIndex');
  926. if (index) {
  927. this.reloadGraphByTime(--index);
  928. }
  929. },
  930. /**
  931. * reload graph depending on the time
  932. * @param index
  933. */
  934. reloadGraphByTime: function (index) {
  935. this.set('currentTimeIndex', index);
  936. self.set('currentTimeIndex', index);
  937. },
  938. currentTimeIndex: self.get('currentTimeIndex'),
  939. currentTimeState: function () {
  940. return self.get('timeStates').objectAt(this.get('currentTimeIndex'));
  941. }.property('currentTimeIndex')
  942. });
  943. Em.run.next(function () {
  944. self.loadData();
  945. self.set('isPopupReady', false);
  946. });
  947. },
  948. reloadGraphByTime: function () {
  949. this.loadData();
  950. }.observes('timeUnitSeconds'),
  951. timeStates: [
  952. {name: Em.I18n.t('graphs.timeRange.hour'), seconds: 3600},
  953. {name: Em.I18n.t('graphs.timeRange.twoHours'), seconds: 7200},
  954. {name: Em.I18n.t('graphs.timeRange.fourHours'), seconds: 14400},
  955. {name: Em.I18n.t('graphs.timeRange.twelveHours'), seconds: 43200},
  956. {name: Em.I18n.t('graphs.timeRange.day'), seconds: 86400},
  957. {name: Em.I18n.t('graphs.timeRange.week'), seconds: 604800},
  958. {name: Em.I18n.t('graphs.timeRange.month'), seconds: 2592000},
  959. {name: Em.I18n.t('graphs.timeRange.year'), seconds: 31104000}
  960. ],
  961. // should be set by time range control dropdown list when create current graph
  962. currentTimeIndex: 0,
  963. setCurrentTimeIndexFromParent: function () {
  964. var index = !Em.isNone(this.get('parentView.currentTimeRangeIndex')) ? this.get('parentView.currentTimeRangeIndex') : this.get('parentView.parentView.currentTimeRangeIndex');
  965. this.set('currentTimeIndex', index);
  966. }.observes('parentView.parentView.currentTimeRangeIndex', 'parentView.currentTimeRangeIndex'),
  967. timeUnitSeconds: function () {
  968. return this.get('timeStates').objectAt(this.get('currentTimeIndex')).seconds;
  969. }.property('currentTimeIndex')
  970. });
  971. /**
  972. * A formatter which will turn a number into computer storage sizes of the
  973. * format '23 GB' etc.
  974. *
  975. * @type {Function}
  976. * @return {string}
  977. */
  978. App.ChartLinearTimeView.BytesFormatter = function (y) {
  979. if (0 == y) {
  980. return '0 B';
  981. }
  982. var value = Rickshaw.Fixtures.Number.formatBase1024KMGTP(y);
  983. if (!y) {
  984. return '0 B';
  985. }
  986. if ("number" == typeof value) {
  987. value = String(value);
  988. }
  989. if ("string" == typeof value) {
  990. value = value.replace(/\.\d(\d+)/, function ($0, $1) { // Remove only 1-digit after decimal part
  991. return $0.replace($1, '');
  992. });
  993. // Either it ends with digit or ends with character
  994. value = value.replace(/(\d$)/, '$1 '); // Ends with digit like '120'
  995. value = value.replace(/([a-zA-Z]$)/, ' $1'); // Ends with character like
  996. // '120M'
  997. value = value + 'B'; // Append B to make B, MB, GB etc.
  998. }
  999. return value;
  1000. };
  1001. /**
  1002. * A formatter which will turn a number into percentage display like '42%'
  1003. *
  1004. * @type {Function}
  1005. * @param {number} percentage
  1006. * @return {string}
  1007. */
  1008. App.ChartLinearTimeView.PercentageFormatter = function (percentage) {
  1009. return percentage ?
  1010. percentage.toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + '%' :
  1011. '0 %';
  1012. };
  1013. /**
  1014. * A formatter which will turn a number into percentage display like '42%'
  1015. *
  1016. * @type {Function}
  1017. * @param {number} value
  1018. * @param {string} displayUnit
  1019. * @return {string}
  1020. */
  1021. App.ChartLinearTimeView.DisplayUnitFormatter = function (value, displayUnit) {
  1022. return value ?
  1023. value.toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + " " + displayUnit :
  1024. '0 ' + displayUnit;
  1025. };
  1026. /**
  1027. * A formatter which will turn elapsed time into display time like '50 ms',
  1028. * '5s', '10 m', '3 hr' etc. Time is expected to be provided in milliseconds.
  1029. *
  1030. * @type {Function}
  1031. * @return {string}
  1032. */
  1033. App.ChartLinearTimeView.TimeElapsedFormatter = function (millis) {
  1034. if (!millis) {
  1035. return '0 ms';
  1036. }
  1037. if ('number' == Em.typeOf(millis)) {
  1038. var seconds = millis > 1000 ? Math.round(millis / 1000) : 0;
  1039. var minutes = seconds > 60 ? Math.round(seconds / 60) : 0;
  1040. var hours = minutes > 60 ? Math.round(minutes / 60) : 0;
  1041. var days = hours > 24 ? Math.round(hours / 24) : 0;
  1042. if (days > 0) {
  1043. return days + ' d';
  1044. }
  1045. if (hours > 0) {
  1046. return hours + ' hr';
  1047. }
  1048. if (minutes > 0) {
  1049. return minutes + ' m';
  1050. }
  1051. if (seconds > 0) {
  1052. return seconds + ' s';
  1053. }
  1054. return millis.toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + ' ms';
  1055. }
  1056. return millis;
  1057. };
  1058. /**
  1059. * The default formatter which uses Rickshaw.Fixtures.Number.formatKMBT
  1060. * which shows 10K, 300M etc.
  1061. *
  1062. * @type {Function}
  1063. * @return {string|number}
  1064. */
  1065. App.ChartLinearTimeView.DefaultFormatter = function (y) {
  1066. if (!y) {
  1067. return 0;
  1068. }
  1069. var value = Rickshaw.Fixtures.Number.formatKMBT(y);
  1070. if ('' == value) return '0';
  1071. value = String(value);
  1072. var c = value[value.length - 1];
  1073. return isNaN(parseInt(c)) ?
  1074. parseFloat(value.substr(0, value.length - 1)).toFixed(3).replace(/0+$/, '').replace(/\.$/, '') + c :
  1075. parseFloat(value).toFixed(3).replace(/0+$/, '').replace(/\.$/, '');
  1076. };
  1077. /**
  1078. * Creates and returns a formatter that can convert a 'value'
  1079. * to 'value units/s'.
  1080. *
  1081. * @param unitsPrefix Prefix which will be used in 'unitsPrefix/s'
  1082. * @param valueFormatter Value itself will need further processing
  1083. * via provided formatter. Ex: '10M requests/s'. Generally
  1084. * should be App.ChartLinearTimeView.DefaultFormatter.
  1085. * @return {Function}
  1086. */
  1087. App.ChartLinearTimeView.CreateRateFormatter = function (unitsPrefix, valueFormatter) {
  1088. var suffix = " " + unitsPrefix + "/s";
  1089. return function (value) {
  1090. value = valueFormatter(value) + suffix;
  1091. return value;
  1092. };
  1093. };
  1094. Rickshaw.GraphReopened = function (a) {
  1095. Rickshaw.Graph.call(this, a);
  1096. };
  1097. //reopened in order to exclude "null" value from validation
  1098. Rickshaw.GraphReopened.prototype = Object.create(Rickshaw.Graph.prototype, {
  1099. validateSeries: {
  1100. value: function (series) {
  1101. if (!(series instanceof Array) && !(series instanceof Rickshaw.Series)) {
  1102. var seriesSignature = Object.prototype.toString.apply(series);
  1103. throw "series is not an array: " + seriesSignature;
  1104. }
  1105. var pointsCount;
  1106. series.forEach(function (s) {
  1107. if (!(s instanceof Object)) {
  1108. throw "series element is not an object: " + s;
  1109. }
  1110. if (!(s.data)) {
  1111. throw "series has no data: " + JSON.stringify(s);
  1112. }
  1113. if (!(s.data instanceof Array)) {
  1114. throw "series data is not an array: " + JSON.stringify(s.data);
  1115. }
  1116. pointsCount = pointsCount || s.data.length;
  1117. if (pointsCount && s.data.length != pointsCount) {
  1118. throw "series cannot have differing numbers of points: " +
  1119. pointsCount + " vs " + s.data.length + "; see Rickshaw.Series.zeroFill()";
  1120. }
  1121. })
  1122. },
  1123. enumerable: true,
  1124. configurable: false,
  1125. writable: false
  1126. }
  1127. });
  1128. //show no line if point is "null"
  1129. Rickshaw.Graph.Renderer.Line.prototype.seriesPathFactory = function () {
  1130. var graph = this.graph;
  1131. return d3.svg.line()
  1132. .x(function (d) {
  1133. return graph.x(d.x)
  1134. })
  1135. .y(function (d) {
  1136. return graph.y(d.y)
  1137. })
  1138. .defined(function (d) {
  1139. return d.y != null;
  1140. })
  1141. .interpolate(this.graph.interpolation).tension(this.tension);
  1142. };
  1143. //show no area if point is null
  1144. Rickshaw.Graph.Renderer.Stack.prototype.seriesPathFactory = function () {
  1145. var graph = this.graph;
  1146. return d3.svg.area()
  1147. .x(function (d) {
  1148. return graph.x(d.x)
  1149. })
  1150. .y0(function (d) {
  1151. return graph.y(d.y0)
  1152. })
  1153. .y1(function (d) {
  1154. return graph.y(d.y + d.y0)
  1155. })
  1156. .defined(function (d) {
  1157. return d.y != null;
  1158. })
  1159. .interpolate(this.graph.interpolation).tension(this.tension);
  1160. };
  1161. /**
  1162. * aggregate requests to load metrics by component name
  1163. * requests can be added via add method
  1164. * input example:
  1165. * {
  1166. * data: request,
  1167. * context: this,
  1168. * startCallName: this.getServiceComponentMetrics,
  1169. * successCallback: this.getMetricsSuccessCallback,
  1170. * completeCallback: function () {
  1171. * requestCounter--;
  1172. * if (requestCounter === 0) this.onMetricsLoaded();
  1173. * }
  1174. * }
  1175. * @type {Em.Object}
  1176. */
  1177. App.ChartLinearTimeView.LoadAggregator = Em.Object.create({
  1178. /**
  1179. * @type {Array}
  1180. */
  1181. requests: [],
  1182. /**
  1183. * @type {number|null}
  1184. */
  1185. timeoutId: null,
  1186. /**
  1187. * time interval within which calls get collected
  1188. * @type {number}
  1189. * @const
  1190. */
  1191. BULK_INTERVAL: 1000,
  1192. /**
  1193. * add request
  1194. * every {{BULK_INTERVAL}} requests get collected, aggregated and sent to server
  1195. *
  1196. * @param {object} context
  1197. * @param {object} requestData
  1198. */
  1199. add: function (context, requestData) {
  1200. var self = this;
  1201. requestData.context = context;
  1202. this.get('requests').push(requestData);
  1203. if (Em.isNone(this.get('timeoutId'))) {
  1204. this.set('timeoutId', window.setTimeout(function () {
  1205. self.runRequests(self.get('requests'));
  1206. self.get('requests').clear();
  1207. clearTimeout(self.get('timeoutId'));
  1208. self.set('timeoutId', null);
  1209. }, this.get('BULK_INTERVAL')));
  1210. }
  1211. },
  1212. /**
  1213. * return requests which grouped into bulks
  1214. * @param {Array} requests
  1215. * @returns {object} bulks
  1216. */
  1217. groupRequests: function (requests) {
  1218. var bulks = {};
  1219. requests.forEach(function (request) {
  1220. var id = request.name;
  1221. if (Em.isNone(bulks[id])) {
  1222. bulks[id] = {
  1223. name: request.name,
  1224. fields: request.fields.slice(),
  1225. context: request.context
  1226. };
  1227. bulks[id].subRequests = [{
  1228. context: request.context
  1229. }];
  1230. } else {
  1231. bulks[id].fields.pushObjects(request.fields);
  1232. bulks[id].subRequests.push({
  1233. context: request.context
  1234. });
  1235. }
  1236. }, this);
  1237. return bulks;
  1238. },
  1239. /**
  1240. * run aggregated requests
  1241. * @param {Array} requests
  1242. */
  1243. runRequests: function (requests) {
  1244. var bulks = this.groupRequests(requests);
  1245. var self = this;
  1246. for (var id in bulks) {
  1247. (function (_request) {
  1248. var fields = self.formatRequestData(_request);
  1249. var hostName = (_request.context.get('content')) ? _request.context.get('content.hostName') : "";
  1250. App.ajax.send({
  1251. name: _request.name,
  1252. sender: _request.context,
  1253. data: {
  1254. fields: fields,
  1255. hostName: hostName
  1256. }
  1257. }).done(function (response) {
  1258. console.time('==== runRequestsDone');
  1259. _request.subRequests.forEach(function (subRequest) {
  1260. subRequest.context._refreshGraph.call(subRequest.context, response);
  1261. }, this);
  1262. console.timeEnd('==== runRequestsDone');
  1263. }).fail(function (jqXHR, textStatus, errorThrown) {
  1264. _request.subRequests.forEach(function (subRequest) {
  1265. subRequest.context.loadDataErrorCallback.call(subRequest.context, jqXHR, textStatus, errorThrown);
  1266. }, this);
  1267. });
  1268. })(bulks[id]);
  1269. }
  1270. },
  1271. /**
  1272. *
  1273. * @param {object} request
  1274. * @returns {number[]}
  1275. */
  1276. formatRequestData: function (request) {
  1277. var toSeconds = Math.round(App.dateTime() / 1000);
  1278. var timeUnit = request.context.get('timeUnitSeconds');
  1279. var fields = request.fields.uniq().map(function (field) {
  1280. return field + "[" + (toSeconds - timeUnit) + "," + toSeconds + "," + 15 + "]";
  1281. });
  1282. return fields.join(",");
  1283. }
  1284. });