helper.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. var stringUtils = require('utils/string_utils');
  19. var timezoneUtils = require('utils/date/timezone');
  20. /**
  21. * Remove spaces at beginning and ending of line.
  22. * @example
  23. * var str = " I'm a string "
  24. * str.trim() // return "I'm a string"
  25. * @method trim
  26. * @return {string}
  27. */
  28. String.prototype.trim = function () {
  29. return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  30. };
  31. /**
  32. * Determines whether string end within another string.
  33. *
  34. * @method endsWith
  35. * @param suffix {string} substring for search
  36. * @return {boolean}
  37. */
  38. String.prototype.endsWith = function(suffix) {
  39. return this.indexOf(suffix, this.length - suffix.length) !== -1;
  40. };
  41. /**
  42. * Determines whether string start within another string.
  43. *
  44. * @method startsWith
  45. * @param prefix {string} substring for search
  46. * @return {boolean}
  47. */
  48. String.prototype.startsWith = function (prefix){
  49. return this.indexOf(prefix) == 0;
  50. };
  51. /**
  52. * Determines whether string founded within another string.
  53. *
  54. * @method contains
  55. * @param substring {string} substring for search
  56. * @return {boolean}
  57. */
  58. String.prototype.contains = function(substring) {
  59. return this.indexOf(substring) != -1;
  60. };
  61. /**
  62. * Capitalize the first letter of string.
  63. * @method capitalize
  64. * @return {string}
  65. */
  66. String.prototype.capitalize = function () {
  67. return this.charAt(0).toUpperCase() + this.slice(1);
  68. };
  69. /**
  70. * Capitalize the first letter of string.
  71. * And set to lowercase other part of string
  72. * @method toCapital
  73. * @return {string}
  74. */
  75. String.prototype.toCapital = function () {
  76. return this.charAt(0).toUpperCase() + this.slice(1).toLowerCase();
  77. };
  78. /**
  79. * Finds the value in an object where this string is a key.
  80. * Optionally, the index of the key can be provided where the
  81. * value of the nth key in the hierarchy is returned.
  82. *
  83. * Example:
  84. * var tofind = 'smart';
  85. * var person = {'name': 'Bob Bob', 'smart': 'no', 'age': '28', 'personality': {'smart': 'yes', 'funny': 'yes', 'emotion': 'happy'} };
  86. * tofind.findIn(person); // 'no'
  87. * tofind.findIn(person, 0); // 'no'
  88. * tofind.findIn(person, 1); // 'yes'
  89. * tofind.findIn(person, 2); // null
  90. *
  91. * @method findIn
  92. * @param multi {object}
  93. * @param index {number} Occurrence count of this key
  94. * @return {*} Value of key at given index
  95. */
  96. String.prototype.findIn = function(multi, index, _foundValues) {
  97. if (!index) {
  98. index = 0;
  99. }
  100. if (!_foundValues) {
  101. _foundValues = [];
  102. }
  103. multi = multi || '';
  104. var value = null;
  105. var str = this.valueOf();
  106. if (typeof multi == 'object') {
  107. for ( var key in multi) {
  108. if (value != null) {
  109. break;
  110. }
  111. if (key == str) {
  112. _foundValues.push(multi[key]);
  113. }
  114. if (_foundValues.length - 1 == index) {
  115. // Found the value
  116. return _foundValues[index];
  117. }
  118. if (typeof multi[key] == 'object') {
  119. value = value || this.findIn(multi[key], index, _foundValues);
  120. }
  121. }
  122. }
  123. return value;
  124. };
  125. /**
  126. * Replace {i} with argument. where i is number of argument to replace with.
  127. * @example
  128. * var str = "{0} world{1}";
  129. * str.format("Hello", "!") // return "Hello world!"
  130. *
  131. * @method format
  132. * @return {string}
  133. */
  134. String.prototype.format = function () {
  135. var args = arguments;
  136. return this.replace(/{(\d+)}/g, function (match, number) {
  137. return typeof args[number] != 'undefined' ? args[number] : match;
  138. });
  139. };
  140. /**
  141. * Wrap words in string within template.
  142. *
  143. * @method highlight
  144. * @param {string[]} words - words to wrap
  145. * @param {string} [highlightTemplate="<b>{0}</b>"] - template for wrapping
  146. * @return {string}
  147. */
  148. String.prototype.highlight = function (words, highlightTemplate) {
  149. var self = this;
  150. highlightTemplate = highlightTemplate ? highlightTemplate : "<b>{0}</b>";
  151. words.forEach(function (word) {
  152. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  153. self = self.replace(searchRegExp, function (found) {
  154. return highlightTemplate.format(found);
  155. });
  156. });
  157. return self;
  158. };
  159. /**
  160. * Convert time in milliseconds to object contained days, hours and minutes.
  161. * @typedef ConvertedTime
  162. * @type {Object}
  163. * @property {number} d - days
  164. * @property {number} h - hours
  165. * @property {string} m - minutes
  166. * @example
  167. * var time = 1000000000;
  168. * time.toDaysHoursMinutes() // {d: 11, h: 13, m: "46.67"}
  169. *
  170. * @method toDaysHoursMinutes
  171. * @return {object}
  172. */
  173. Number.prototype.toDaysHoursMinutes = function () {
  174. var formatted = {},
  175. dateDiff = this,
  176. secK = 1000, //ms
  177. minK = 60 * secK, // sec
  178. hourK = 60 * minK, // sec
  179. dayK = 24 * hourK;
  180. dateDiff = parseInt(dateDiff);
  181. formatted.d = Math.floor(dateDiff / dayK);
  182. dateDiff -= formatted.d * dayK;
  183. formatted.h = Math.floor(dateDiff / hourK);
  184. dateDiff -= formatted.h * hourK;
  185. formatted.m = (dateDiff / minK).toFixed(2);
  186. return formatted;
  187. };
  188. /**
  189. *
  190. * @param bound1 {Number}
  191. * @param bound2 {Number}
  192. * @return {boolean}
  193. */
  194. Number.prototype.isInRange = function (bound1, bound2) {
  195. var upperBound, lowerBound;
  196. upperBound = bound1 > bound2 ? bound1: bound2;
  197. lowerBound = bound1 < bound2 ? bound1: bound2;
  198. return this > lowerBound && this < upperBound;
  199. };
  200. /**
  201. Sort an array by the key specified in the argument.
  202. Handle only native js objects as element of array, not the Ember's object.
  203. Can be used as alternative to sortProperty method of Ember library
  204. in order to speed up executing on large data volumes
  205. @method sortBy
  206. @param {String} path name(s) to sort on
  207. @return {Array} The sorted array.
  208. */
  209. Array.prototype.sortPropertyLight = function (path) {
  210. var realPath = (typeof path === "string") ? path.split('.') : [];
  211. this.sort(function (a, b) {
  212. var aProperty = a;
  213. var bProperty = b;
  214. realPath.forEach(function (key) {
  215. aProperty = aProperty[key];
  216. bProperty = bProperty[key];
  217. });
  218. if (aProperty > bProperty) return 1;
  219. if (aProperty < bProperty) return -1;
  220. return 0;
  221. });
  222. return this;
  223. };
  224. /**
  225. * Create map from array with executing provided callback for each array's item
  226. * Example:
  227. * <pre>
  228. * var array = [{a: 1, b: 3}, {a: 2, b: 2}, {a: 3, b: 1}];
  229. * var map = array.toMapByCallback('a', function (item) {
  230. * return Em.get(item, 'b');
  231. * });
  232. * console.log(map); // {1: 3, 2: 2, 3: 1}
  233. * </pre>
  234. * <code>map[1]</code> is much more faster than <code>array.findProperty('a', 1).get('b')</code>
  235. *
  236. * @param {string} property
  237. * @param {Function} callback
  238. * @returns {object}
  239. * @method toMapByCallback
  240. */
  241. Array.prototype.toMapByCallback = function (property, callback) {
  242. var ret = {};
  243. Em.assert('`property` can\'t be empty string', property.length);
  244. Em.assert('`callback` should be a function', 'function' === Em.typeOf(callback));
  245. this.forEach(function (item) {
  246. var key = Em.get(item, property);
  247. ret[key] = callback(item, property);
  248. });
  249. return ret;
  250. };
  251. /**
  252. * Create map from array
  253. * Example:
  254. * <pre>
  255. * var array = [{a: 1}, {a: 2}, {a: 3}];
  256. * var map = array.toMapByProperty('a'); // {1: {a: 1}, 2: {a: 2}, 3: {a: 3}}
  257. * </pre>
  258. * <code>map[1]</code> is much more faster than <code>array.findProperty('a', 1)</code>
  259. *
  260. * @param {string} property
  261. * @return {object}
  262. * @method toMapByProperty
  263. * @see toMapByCallback
  264. */
  265. Array.prototype.toMapByProperty = function (property) {
  266. return this.toMapByCallback(property, function (item) {
  267. return item;
  268. });
  269. };
  270. /**
  271. * Create wick map from array
  272. * Example:
  273. * <pre>
  274. * var array = [{a: 1}, {a: 2}, {a: 3}];
  275. * var map = array.toWickMapByProperty('a'); // {1: true, 2: true, 3: true}
  276. * </pre>
  277. * <code>map[1]</code> works faster than <code>array.someProperty('a', 1)</code>
  278. *
  279. * @param {string} property
  280. * @return {object}
  281. * @method toWickMapByProperty
  282. * @see toMapByCallback
  283. */
  284. Array.prototype.toWickMapByProperty = function (property) {
  285. return this.toMapByCallback(property, function () {
  286. return true;
  287. });
  288. };
  289. /**
  290. * Create wick map from array of primitives
  291. * Example:
  292. * <pre>
  293. * var array = [1, 2, 3];
  294. * var map = array.toWickMap(); // {1: true, 2: true, 3: true}
  295. * </pre>
  296. * <code>map[1]</code> works faster than <code>array.contains(1)</code>
  297. *
  298. * @returns {object}
  299. * @method toWickMap
  300. */
  301. Array.prototype.toWickMap = function () {
  302. var ret = {};
  303. this.forEach(function (item) {
  304. ret[item] = true;
  305. });
  306. return ret;
  307. };
  308. /** @namespace Em **/
  309. Em.CoreObject.reopen({
  310. t:function (key, attrs) {
  311. return Em.I18n.t(key, attrs)
  312. }
  313. });
  314. Em.TextArea.reopen(Em.I18n.TranslateableAttributes);
  315. /** @namespace Em.Handlebars **/
  316. Em.Handlebars.registerHelper('log', function (variable) {
  317. console.log(variable);
  318. });
  319. Em.Handlebars.registerHelper('warn', function (variable) {
  320. console.warn(variable);
  321. });
  322. Em.Handlebars.registerHelper('highlight', function (property, words, fn) {
  323. var context = (fn.contexts && fn.contexts[0]) || this;
  324. property = Em.Handlebars.getPath(context, property, fn);
  325. words = words.split(";");
  326. // if (highlightTemplate == undefined) {
  327. var highlightTemplate = "<b>{0}</b>";
  328. // }
  329. words.forEach(function (word) {
  330. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  331. property = property.replace(searchRegExp, function (found) {
  332. return highlightTemplate.format(found);
  333. });
  334. });
  335. return new Em.Handlebars.SafeString(property);
  336. });
  337. /**
  338. * Usage:
  339. *
  340. * <pre>
  341. * {{#isAuthorized "SERVICE.TOGGLE_ALERTS"}}
  342. * {{! some truly code }}
  343. * {{else}}
  344. * {{! some falsy code }}
  345. * {{/isAuthorized}}
  346. * </pre>
  347. */
  348. Em.Handlebars.registerHelper('isAuthorized', function (property, options) {
  349. var permission = Ember.Object.create({
  350. isAuthorized: function() {
  351. return App.isAuthorized(property);
  352. }.property('App.router.wizardWatcherController.isWizardRunning')
  353. });
  354. // wipe out contexts so boundIf uses `this` (the permission) as the context
  355. options.contexts = null;
  356. return Ember.Handlebars.helpers.boundIf.call(permission, "isAuthorized", options);
  357. });
  358. /**
  359. * @namespace App
  360. */
  361. App = require('app');
  362. /**
  363. * Certain variables can have JSON in string
  364. * format, or in JSON format itself.
  365. *
  366. * @memberof App
  367. * @function parseJson
  368. * @param {string|object}
  369. * @return {object}
  370. */
  371. App.parseJSON = function (value) {
  372. if (typeof value == "string") {
  373. return jQuery.parseJSON(value);
  374. }
  375. return value;
  376. };
  377. /**
  378. * Check for empty <code>Object</code>, built in Em.isEmpty()
  379. * doesn't support <code>Object</code> type
  380. *
  381. * @memberof App
  382. * @method isEmptyObject
  383. * @param obj {Object}
  384. * @return {Boolean}
  385. */
  386. App.isEmptyObject = function(obj) {
  387. var empty = true;
  388. for (var prop in obj) { if (obj.hasOwnProperty(prop)) {empty = false; break;} }
  389. return empty;
  390. };
  391. /**
  392. * Convert object under_score keys to camelCase
  393. *
  394. * @param {Object} object
  395. * @return {Object}
  396. **/
  397. App.keysUnderscoreToCamelCase = function(object) {
  398. var tmp = {};
  399. for (var key in object) {
  400. tmp[stringUtils.underScoreToCamelCase(key)] = object[key];
  401. }
  402. return tmp;
  403. };
  404. /**
  405. * Convert dotted keys to camelcase
  406. *
  407. * @param {Object} object
  408. * @return {Object}
  409. **/
  410. App.keysDottedToCamelCase = function(object) {
  411. var tmp = {};
  412. for (var key in object) {
  413. tmp[key.split('.').reduce(function(p, c) { return p + c.capitalize()})] = object[key];
  414. }
  415. return tmp;
  416. };
  417. /**
  418. * Returns object with defined keys only.
  419. *
  420. * @memberof App
  421. * @method permit
  422. * @param {Object} obj - input object
  423. * @param {String|Array} keys - allowed keys
  424. * @return {Object}
  425. */
  426. App.permit = function(obj, keys) {
  427. var result = {};
  428. if (typeof obj !== 'object' || App.isEmptyObject(obj)) return result;
  429. if (typeof keys == 'string') keys = Array(keys);
  430. keys.forEach(function(key) {
  431. if (obj.hasOwnProperty(key))
  432. result[key] = obj[key];
  433. });
  434. return result;
  435. };
  436. /**
  437. *
  438. * @namespace App
  439. * @namespace App.format
  440. */
  441. App.format = {
  442. /**
  443. * @memberof App.format
  444. * @type {object}
  445. * @property components
  446. */
  447. components: {
  448. 'API': 'API',
  449. 'DECOMMISSION_DATANODE': 'Update Exclude File',
  450. 'DRPC': 'DRPC',
  451. 'FLUME_HANDLER': 'Flume',
  452. 'GLUSTERFS': 'GLUSTERFS',
  453. 'HBASE': 'HBase',
  454. 'HBASE_REGIONSERVER': 'RegionServer',
  455. 'HCAT': 'HCat Client',
  456. 'HDFS': 'HDFS',
  457. 'HISTORYSERVER': 'History Server',
  458. 'HIVE_SERVER': 'HiveServer2',
  459. 'JCE': 'JCE',
  460. 'MAPREDUCE2': 'MapReduce2',
  461. 'MYSQL': 'MySQL',
  462. 'REST': 'REST',
  463. 'SECONDARY_NAMENODE': 'SNameNode',
  464. 'STORM_REST_API': 'Storm REST API Server',
  465. 'WEBHCAT': 'WebHCat',
  466. 'YARN': 'YARN',
  467. 'UI': 'UI',
  468. 'ZKFC': 'ZKFailoverController',
  469. 'ZOOKEEPER': 'ZooKeeper',
  470. 'ZOOKEEPER_QUORUM_SERVICE_CHECK': 'ZK Quorum Service Check'
  471. },
  472. /**
  473. * @memberof App.format
  474. * @property command
  475. * @type {object}
  476. */
  477. command: {
  478. 'INSTALL': 'Install',
  479. 'UNINSTALL': 'Uninstall',
  480. 'START': 'Start',
  481. 'STOP': 'Stop',
  482. 'EXECUTE': 'Execute',
  483. 'ABORT': 'Abort',
  484. 'UPGRADE': 'Upgrade',
  485. 'RESTART': 'Restart',
  486. 'SERVICE_CHECK': 'Check',
  487. 'Excluded:': 'Decommission:',
  488. 'Included:': 'Recommission:'
  489. },
  490. /**
  491. * cached map of service names
  492. * @type {object}
  493. */
  494. stackServiceRolesMap: {},
  495. /**
  496. * cached map of component names
  497. * @type {object}
  498. */
  499. stackComponentRolesMap: {},
  500. /**
  501. * convert role to readable string
  502. *
  503. * @memberof App.format
  504. * @method role
  505. * @param {string} role
  506. * @param {boolean} isServiceRole
  507. * return {string}
  508. */
  509. role: function (role, isServiceRole) {
  510. if (isServiceRole) {
  511. var model = App.StackService;
  512. var map = this.stackServiceRolesMap;
  513. } else {
  514. var model = App.StackServiceComponent;
  515. var map = this.stackComponentRolesMap;
  516. }
  517. this.initializeStackRolesMap(map, model);
  518. if (map[role]) {
  519. return map[role];
  520. }
  521. return this.normalizeName(role);
  522. },
  523. initializeStackRolesMap: function (map, model) {
  524. if (App.isEmptyObject(map)) {
  525. model.find().forEach(function (item) {
  526. map[item.get('id')] = item.get('displayName');
  527. });
  528. }
  529. },
  530. /**
  531. * Try to format non predefined names to readable format.
  532. *
  533. * @method normalizeNameBySeparator
  534. * @param name {String} - name to format
  535. * @param separators {String} - token use to split the string
  536. * @return {String}
  537. */
  538. normalizeNameBySeparators: function(name, separators) {
  539. if (!name || typeof name != 'string') return '';
  540. name = name.toLowerCase();
  541. if (!separators || separators.length == 0) {
  542. console.debug("No separators specified. Use default separator '_' instead");
  543. separators = ["_"];
  544. }
  545. for (var i = 0; i < separators.length; i++){
  546. var separator = separators[i];
  547. if (new RegExp(separator, 'g').test(name)) {
  548. name = name.split(separator).map(function(singleName) {
  549. return this.normalizeName(singleName.toUpperCase());
  550. }, this).join(' ');
  551. }
  552. }
  553. return name.capitalize();
  554. },
  555. /**
  556. * Try to format non predefined names to readable format.
  557. *
  558. * @method normalizeName
  559. * @param name {String} - name to format
  560. * @return {String}
  561. */
  562. normalizeName: function(name) {
  563. if (!name || typeof name != 'string') return '';
  564. if (this.components[name]) return this.components[name];
  565. name = name.toLowerCase();
  566. var suffixNoSpaces = ['node','tracker','manager'];
  567. var suffixRegExp = new RegExp('(\\w+)(' + suffixNoSpaces.join('|') + ')', 'gi');
  568. if (/_/g.test(name)) {
  569. name = name.split('_').map(function(singleName) {
  570. return this.normalizeName(singleName.toUpperCase());
  571. }, this).join(' ');
  572. } else if(suffixRegExp.test(name)) {
  573. suffixRegExp.lastIndex = 0;
  574. var matches = suffixRegExp.exec(name);
  575. name = matches[1].capitalize() + matches[2].capitalize();
  576. }
  577. return name.capitalize();
  578. },
  579. /**
  580. * convert command_detail to readable string, show the string for all tasks name
  581. *
  582. * @memberof App.format
  583. * @method commandDetail
  584. * @param {string} command_detail
  585. * @param {string} request_inputs
  586. * @return {string}
  587. */
  588. commandDetail: function (command_detail, request_inputs) {
  589. var detailArr = command_detail.split(' ');
  590. var self = this;
  591. var result = '';
  592. detailArr.forEach( function(item) {
  593. // if the item has the pattern SERVICE/COMPONENT, drop the SERVICE part
  594. if (item.contains('/')) {
  595. item = item.split('/')[1];
  596. }
  597. if (item == 'DECOMMISSION,') {
  598. // ignore text 'DECOMMISSION,'( command came from 'excluded/included'), here get the component name from request_inputs
  599. item = (jQuery.parseJSON(request_inputs)) ? jQuery.parseJSON(request_inputs).slave_type : '';
  600. }
  601. if (self.components[item]) {
  602. result = result + ' ' + self.components[item];
  603. } else if (self.command[item]) {
  604. result = result + ' ' + self.command[item];
  605. } else {
  606. result = result + ' ' + self.role(item, false);
  607. }
  608. });
  609. if (result.indexOf('Decommission:') > -1 || result.indexOf('Recommission:') > -1) {
  610. // for Decommission command, make sure the hostname is in lower case
  611. result = result.split(':')[0] + ': ' + result.split(':')[1].toLowerCase();
  612. }
  613. //TODO check if UI use this
  614. if (result === ' Nagios Update Ignore Actionexecute') {
  615. result = Em.I18n.t('common.maintenance.task');
  616. }
  617. if (result.indexOf('Install Packages Actionexecute') != -1) {
  618. result = Em.I18n.t('common.installRepo.task');
  619. }
  620. if (result === ' Rebalancehdfs NameNode') {
  621. result = Em.I18n.t('services.service.actions.run.rebalanceHdfsNodes.title');
  622. }
  623. if (result === " Startdemoldap Knox Gateway") {
  624. result = Em.I18n.t('services.service.actions.run.startLdapKnox.title');
  625. }
  626. if (result === " Stopdemoldap Knox Gateway") {
  627. result = Em.I18n.t('services.service.actions.run.stopLdapKnox.title');
  628. }
  629. if (result === ' Refreshqueues ResourceManager') {
  630. result = Em.I18n.t('services.service.actions.run.yarnRefreshQueues.title');
  631. }
  632. // HAWQ custom commands on back Ops page.
  633. if (result === ' Resync Hawq Standby HAWQ Standby Master') {
  634. result = Em.I18n.t('services.service.actions.run.resyncHawqStandby.label');
  635. }
  636. if (result === ' Immediate Stop Hawq Service HAWQ Master') {
  637. result = Em.I18n.t('services.service.actions.run.immediateStopHawqService.label');
  638. }
  639. if (result === ' Immediate Stop Hawq Segment HAWQ Segment') {
  640. result = Em.I18n.t('services.service.actions.run.immediateStopHawqSegment.label');
  641. }
  642. if(result === ' Activate Hawq Standby HAWQ Standby Master') {
  643. result = Em.I18n.t('admin.activateHawqStandby.button.enable');
  644. }
  645. if(result === ' Hawq Clear Cache HAWQ Master') {
  646. result = Em.I18n.t('services.service.actions.run.clearHawqCache.label');
  647. }
  648. if(result === ' Run Hawq Check HAWQ Master') {
  649. result = Em.I18n.t('services.service.actions.run.runHawqCheck.label');
  650. }
  651. //<---End HAWQ custom commands--->
  652. return result;
  653. },
  654. /**
  655. * Convert uppercase status name to lowercase.
  656. * <br>
  657. * <br>PENDING - Not queued yet for a host
  658. * <br>QUEUED - Queued for a host
  659. * <br>IN_PROGRESS - Host reported it is working
  660. * <br>COMPLETED - Host reported success
  661. * <br>FAILED - Failed
  662. * <br>TIMEDOUT - Host did not respond in time
  663. * <br>ABORTED - Operation was abandoned
  664. *
  665. * @memberof App.format
  666. * @method taskStatus
  667. * @param {string} _taskStatus
  668. * @return {string}
  669. *
  670. */
  671. taskStatus:function (_taskStatus) {
  672. return _taskStatus.toLowerCase();
  673. },
  674. /**
  675. * simplify kdc error msg
  676. * @param {string} message
  677. * @param {boolean} strict if this flag is true ignore not defined msgs return null
  678. * else return input msg as is;
  679. * @returns {*}
  680. */
  681. kdcErrorMsg: function(message, strict) {
  682. /**
  683. * Error messages for KDC administrator credentials error
  684. * is used for checking if error message is caused by bad KDC credentials
  685. * @type {{missingKDC: string, invalidKDC: string}}
  686. */
  687. var specialMsg = {
  688. "missingKDC": "Missing KDC administrator credentials.",
  689. "invalidKDC": "Invalid KDC administrator credentials.",
  690. "missingRDCForRealm": "Failed to find a KDC for the specified realm - kadmin"
  691. };
  692. for (var m in specialMsg) {
  693. if (specialMsg.hasOwnProperty(m) && message.contains(specialMsg[m]))
  694. return specialMsg[m];
  695. }
  696. return strict ? null : message;
  697. }
  698. };
  699. /**
  700. * wrapper to bootstrap popover
  701. * fix issue when popover stuck on view routing
  702. *
  703. * @memberof App
  704. * @method popover
  705. * @param {DOMElement} self
  706. * @param {object} options
  707. */
  708. App.popover = function (self, options) {
  709. if (!self) return;
  710. self.popover(options);
  711. self.on("remove", function () {
  712. $(this).trigger('mouseleave').off().removeData('popover');
  713. });
  714. };
  715. /**
  716. * wrapper to bootstrap tooltip
  717. * fix issue when tooltip stuck on view routing
  718. * @memberof App
  719. * @method tooltip
  720. * @param {DOMElement} self
  721. * @param {object} options
  722. */
  723. App.tooltip = function (self, options) {
  724. if (!self || !self.tooltip) return;
  725. self.tooltip(options);
  726. /* istanbul ignore next */
  727. self.on("remove", function () {
  728. $(this).trigger('mouseleave').off().removeData('tooltip');
  729. });
  730. };
  731. /**
  732. * wrapper to Date().getTime()
  733. * fix issue when client clock and server clock not sync
  734. *
  735. * @memberof App
  736. * @method dateTime
  737. * @return {Number} timeStamp of current server clock
  738. */
  739. App.dateTime = function() {
  740. return new Date().getTime() + App.clockDistance;
  741. };
  742. /**
  743. *
  744. * @param {number} [x] timestamp
  745. * @returns {number}
  746. */
  747. App.dateTimeWithTimeZone = function (x) {
  748. var timezone = App.router.get('userSettingsController.userSettings.timezone');
  749. if (timezone) {
  750. var tz = Em.getWithDefault(timezone, 'zones.0.value', '');
  751. return moment(moment.tz(x ? new Date(x) : new Date(), tz).toArray()).toDate().getTime();
  752. }
  753. return x || new Date().getTime();
  754. };
  755. App.formatDateTimeWithTimeZone = function (timeStamp, format) {
  756. var timezone = App.router.get('userSettingsController.userSettings.timezone'),
  757. time;
  758. if (timezone) {
  759. var tz = Em.getWithDefault(timezone, 'zones.0.value', '');
  760. time = moment.tz(timeStamp, tz);
  761. } else {
  762. time = moment(timeStamp);
  763. }
  764. return moment(time).format(format);
  765. };
  766. App.getTimeStampFromLocalTime = function (time) {
  767. var timezone = App.router.get('userSettingsController.userSettings.timezone'),
  768. offsetString = '',
  769. date = moment(time).format('YYYY-MM-DD HH:mm:ss');
  770. if (timezone) {
  771. var offset = timezone.utcOffset;
  772. offsetString = moment().utcOffset(offset).format('Z');
  773. }
  774. return moment(date + offsetString).toDate().getTime();
  775. };
  776. /**
  777. * Ambari overrides the default date transformer.
  778. * This is done because of the non-standard data
  779. * sent. For example Nagios sends date as "12345678".
  780. * The problem is that it is a String and is represented
  781. * only in seconds whereas Javascript's Date needs
  782. * milliseconds representation.
  783. */
  784. DS.attr.transforms.date = {
  785. from: function (serialized) {
  786. var type = typeof serialized;
  787. if (type === Em.I18n.t('common.type.string')) {
  788. serialized = parseInt(serialized);
  789. type = typeof serialized;
  790. }
  791. if (type === Em.I18n.t('common.type.number')) {
  792. if (!serialized ){ //serialized timestamp = 0;
  793. return 0;
  794. }
  795. // The number could be seconds or milliseconds.
  796. // If seconds, then the length is 10
  797. // If milliseconds, the length is 13
  798. if (serialized.toString().length < 13) {
  799. serialized = serialized * 1000;
  800. }
  801. return new Date(serialized);
  802. } else if (serialized === null || serialized === undefined) {
  803. // if the value is not present in the data,
  804. // return undefined, not null.
  805. return serialized;
  806. } else {
  807. return null;
  808. }
  809. },
  810. to: function (deserialized) {
  811. if (deserialized instanceof Date) {
  812. return deserialized.getTime();
  813. } else if (deserialized === undefined) {
  814. return undefined;
  815. } else {
  816. return null;
  817. }
  818. }
  819. };
  820. DS.attr.transforms.object = {
  821. from: function(serialized) {
  822. return Ember.none(serialized) ? null : Object(serialized);
  823. },
  824. to: function(deserialized) {
  825. return Ember.none(deserialized) ? null : Object(deserialized);
  826. }
  827. };
  828. /**
  829. * Allows EmberData models to have array properties.
  830. *
  831. * Declare the property as <code>
  832. * operations: DS.attr('array'),
  833. * </code> and
  834. * during load provide a JSON array for value.
  835. *
  836. * This transform simply assigns the same array in both directions.
  837. */
  838. DS.attr.transforms.array = {
  839. from : function(serialized) {
  840. return serialized;
  841. },
  842. to : function(deserialized) {
  843. return deserialized;
  844. }
  845. };
  846. /**
  847. * Utility method to delete all existing records of a DS.Model type from the model's associated map and
  848. * store's persistence layer (recordCache)
  849. * @param type DS.Model Class
  850. */
  851. App.resetDsStoreTypeMap = function(type) {
  852. var allRecords = App.get('store.recordCache'); //This fetches all records in the ember-data persistence layer
  853. var typeMaps = App.get('store.typeMaps');
  854. var guidForType = Em.guidFor(type);
  855. var typeMap = typeMaps[guidForType];
  856. if (typeMap) {
  857. var idToClientIdMap = typeMap.idToCid;
  858. for (var id in idToClientIdMap) {
  859. if (idToClientIdMap.hasOwnProperty(id) && idToClientIdMap[id]) {
  860. delete allRecords[idToClientIdMap[id]]; // deletes the cached copy of the record from the store
  861. }
  862. }
  863. typeMaps[guidForType] = {
  864. idToCid: {},
  865. clientIds: [],
  866. cidToHash: {},
  867. recordArrays: []
  868. };
  869. }
  870. };