linear_time.js 47 KB

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