helper.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. String.prototype.trim = function () {
  19. return this.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  20. };
  21. String.prototype.endsWith = function(suffix) {
  22. return this.indexOf(suffix, this.length - suffix.length) !== -1;
  23. };
  24. String.prototype.startsWith = function (prefix){
  25. return this.indexOf(prefix) == 0;
  26. };
  27. String.prototype.contains = function(substring) {
  28. return this.indexOf(substring) != -1;
  29. };
  30. /**
  31. * convert ip address string to long int
  32. * @return {*}
  33. */
  34. String.prototype.ip2long = function () {
  35. // * example 1: ip2long('192.0.34.166');
  36. // * returns 1: 3221234342
  37. // * example 2: ip2long('0.0xABCDEF');
  38. // * returns 2: 11259375
  39. // * example 3: ip2long('255.255.255.256');
  40. // * returns 3: false
  41. var i = 0;
  42. // PHP allows decimal, octal, and hexadecimal IP components.
  43. // PHP allows between 1 (e.g. 127) to 4 (e.g 127.0.0.1) components.
  44. var IP = this.match(/^([1-9]\d*|0[0-7]*|0x[\da-f]+)(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?(?:\.([1-9]\d*|0[0-7]*|0x[\da-f]+))?$/i); // Verify IP format.
  45. if (!IP) {
  46. return false; // Invalid format.
  47. }
  48. // Reuse IP variable for component counter.
  49. IP[0] = 0;
  50. for (i = 1; i < 5; i += 1) {
  51. IP[0] += !!((IP[i] || '').length);
  52. IP[i] = parseInt(IP[i]) || 0;
  53. }
  54. // Continue to use IP for overflow values.
  55. // PHP does not allow any component to overflow.
  56. IP.push(256, 256, 256, 256);
  57. // Recalculate overflow of last component supplied to make up for missing components.
  58. IP[4 + IP[0]] *= Math.pow(256, 4 - IP[0]);
  59. if (IP[1] >= IP[5] || IP[2] >= IP[6] || IP[3] >= IP[7] || IP[4] >= IP[8]) {
  60. return false;
  61. }
  62. return IP[1] * (IP[0] === 1 || 16777216) + IP[2] * (IP[0] <= 2 || 65536) + IP[3] * (IP[0] <= 3 || 256) + IP[4] * 1;
  63. };
  64. String.prototype.capitalize = function () {
  65. return this.charAt(0).toUpperCase() + this.slice(1);
  66. }
  67. Em.CoreObject.reopen({
  68. t:function (key, attrs) {
  69. return Em.I18n.t(key, attrs)
  70. }
  71. });
  72. Em.Handlebars.registerHelper('log', function (variable) {
  73. console.log(variable);
  74. });
  75. Em.Handlebars.registerHelper('warn', function (variable) {
  76. console.warn(variable);
  77. });
  78. Em.Handlebars.registerHelper('highlight', function (property, words, fn) {
  79. var context = (fn.contexts && fn.contexts[0]) || this;
  80. property = Em.Handlebars.getPath(context, property, fn);
  81. words = words.split(";");
  82. // if (highlightTemplate == undefined) {
  83. var highlightTemplate = "<b>{0}</b>";
  84. // }
  85. words.forEach(function (word) {
  86. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  87. property = property.replace(searchRegExp, function (found) {
  88. return highlightTemplate.format(found);
  89. });
  90. });
  91. return new Em.Handlebars.SafeString(property);
  92. })
  93. /**
  94. * Replace {i} with argument. where i is number of argument to replace with
  95. * @return {String}
  96. */
  97. String.prototype.format = function () {
  98. var args = arguments;
  99. return this.replace(/{(\d+)}/g, function (match, number) {
  100. return typeof args[number] != 'undefined' ? args[number] : match;
  101. });
  102. };
  103. String.prototype.highlight = function (words, highlightTemplate) {
  104. var self = this;
  105. if (highlightTemplate == undefined) {
  106. var highlightTemplate = "<b>{0}</b>";
  107. }
  108. words.forEach(function (word) {
  109. var searchRegExp = new RegExp("\\b" + word + "\\b", "gi");
  110. self = self.replace(searchRegExp, function (found) {
  111. return highlightTemplate.format(found);
  112. });
  113. });
  114. return self;
  115. };
  116. Array.prototype.move = function(from, to) {
  117. this.splice(to, 0, this.splice(from, 1)[0]);
  118. };
  119. Number.prototype.toDaysHoursMinutes = function () {
  120. var formatted = {},
  121. dateDiff = this,
  122. secK = 1000, //ms
  123. minK = 60 * secK, // sec
  124. hourK = 60 * minK, // sec
  125. dayK = 24 * hourK;
  126. dateDiff = parseInt(dateDiff);
  127. formatted.d = Math.floor(dateDiff / dayK);
  128. dateDiff -= formatted.d * dayK;
  129. formatted.h = Math.floor(dateDiff / hourK);
  130. dateDiff -= formatted.h * hourK;
  131. formatted.m = (dateDiff / minK).toFixed(2);
  132. return formatted;
  133. }
  134. Number.prototype.countPercentageRatio = function (maxValue) {
  135. var usedValue = this;
  136. return Math.round((usedValue / maxValue) * 100) + "%";
  137. }
  138. Number.prototype.long2ip = function () {
  139. // http://kevin.vanzonneveld.net
  140. // + original by: Waldo Malqui Silva
  141. // * example 1: long2ip( 3221234342 );
  142. // * returns 1: '192.0.34.166'
  143. if (!isFinite(this))
  144. return false;
  145. return [this >>> 24, this >>> 16 & 0xFF, this >>> 8 & 0xFF, this & 0xFF].join('.');
  146. }
  147. /**
  148. * Formats the given URL template by replacing keys in 'substitutes'
  149. * with their values. If not in App.testMode, the testUrl is used.
  150. *
  151. * The substitution points in urlTemplate should be of format "...{key}..."
  152. * For example "http://apache.org/{projectName}".
  153. * The substitutes can then be{projectName: "Ambari"}.
  154. *
  155. * Keys which will be automatically taken care of are:
  156. * {
  157. * hostName: App.test_hostname,
  158. * fromSeconds: ..., // 1 hour back from now
  159. * toSeconds: ..., // now
  160. * stepSeconds: ..., // 15 seconds by default
  161. * }
  162. *
  163. * @param {String} urlTemplate URL template on which substitutions are to be made
  164. * @param substitutes Object containing keys to be replaced with respective values
  165. * @param {String} testUrl URL to be used if app is not in test mode (!App.testMode)
  166. * @return {String} Formatted URL
  167. */
  168. App = require('app');
  169. App.formatUrl = function (urlTemplate, substitutes, testUrl) {
  170. var formatted = urlTemplate;
  171. if (urlTemplate) {
  172. if (!App.testMode) {
  173. var toSeconds = Math.round(new Date().getTime() / 1000);
  174. var allSubstitutes = {
  175. toSeconds:toSeconds,
  176. fromSeconds:toSeconds - 3600, // 1 hour back
  177. stepSeconds:15, // 15 seconds
  178. hostName:App.test_hostname
  179. };
  180. jQuery.extend(allSubstitutes, substitutes);
  181. for (key in allSubstitutes) {
  182. var useKey = '{' + key + '}';
  183. formatted = formatted.replace(new RegExp(useKey, 'g'), allSubstitutes[key]);
  184. }
  185. } else {
  186. formatted = testUrl;
  187. }
  188. }
  189. return formatted;
  190. }
  191. /**
  192. * Certain variables can have JSON in string
  193. * format, or in JSON format itself.
  194. */
  195. App.parseJSON = function (value) {
  196. if (typeof value == "string") {
  197. return jQuery.parseJSON(value);
  198. }
  199. return value;
  200. };
  201. App.format = {
  202. role:function (role) {
  203. switch (role) {
  204. case 'ZOOKEEPER_SERVER':
  205. return 'ZooKeeper Server';
  206. case 'ZOOKEEPER_CLIENT':
  207. return 'ZooKeeper Client';
  208. case 'NAMENODE':
  209. return 'NameNode';
  210. case 'NAMENODE_SERVICE_CHECK':
  211. return 'NameNode Service Check';
  212. case 'DATANODE':
  213. return 'DataNode';
  214. case 'JOURNALNODE':
  215. return 'JournalNode';
  216. case 'HDFS_SERVICE_CHECK':
  217. return 'HDFS Service Check';
  218. case 'SECONDARY_NAMENODE':
  219. return 'SNameNode';
  220. case 'HDFS_CLIENT':
  221. return 'HDFS Client';
  222. case 'HBASE_MASTER':
  223. return 'HBase Master';
  224. case 'HBASE_REGIONSERVER':
  225. return 'HBase RegionServer';
  226. case 'HBASE_CLIENT':
  227. return 'HBase Client';
  228. case 'JOBTRACKER':
  229. return 'JobTracker';
  230. case 'TASKTRACKER':
  231. return 'TaskTracker';
  232. case 'MAPREDUCE_CLIENT':
  233. return 'MapReduce Client';
  234. case 'HISTORYSERVER':
  235. return 'History Server';
  236. case 'NODEMANAGER':
  237. return 'NodeManager';
  238. case 'RESOURCEMANAGER':
  239. return 'ResourceManager';
  240. case 'TEZ_CLIENT':
  241. return 'Tez Client';
  242. case 'MAPREDUCE2_CLIENT':
  243. return 'MapReduce2 Client';
  244. case 'YARN_CLIENT':
  245. return 'YARN Client';
  246. case 'JAVA_JCE':
  247. return 'Java JCE';
  248. case 'KERBEROS_SERVER':
  249. return 'Kerberos Server';
  250. case 'KERBEROS_CLIENT':
  251. return 'Kerberos Client';
  252. case 'KERBEROS_ADMIN_CLIENT':
  253. return 'Kerberos Admin Client';
  254. case 'HADOOP_CLIENT':
  255. return 'Hadoop Client';
  256. case 'JOBTRACKER_SERVICE_CHECK':
  257. return 'JobTracker Service Check';
  258. case 'MAPREDUCE_SERVICE_CHECK':
  259. return 'MapReduce Service Check';
  260. case 'ZOOKEEPER_SERVICE_CHECK':
  261. return 'ZooKeeper Service Check';
  262. case 'ZOOKEEPER_QUORUM_SERVICE_CHECK':
  263. return 'ZK Quorum Service Check';
  264. case 'HBASE_SERVICE_CHECK':
  265. return 'HBase Service Check';
  266. case 'MYSQL_SERVER':
  267. return 'MySQL Server';
  268. case 'HIVE_SERVER':
  269. return 'HiveServer2';
  270. case 'HIVE_METASTORE':
  271. return 'Hive Metastore';
  272. case 'HIVE_CLIENT':
  273. return 'Hive Client';
  274. case 'HIVE_SERVICE_CHECK':
  275. return 'Hive Service Check';
  276. case 'HCAT':
  277. return 'HCat';
  278. case 'HCAT_SERVICE_CHECK':
  279. return 'HCat Service Check';
  280. case 'OOZIE_CLIENT':
  281. return 'Oozie Client';
  282. case 'OOZIE_SERVER':
  283. return 'Oozie Server';
  284. case 'OOZIE_SERVICE_CHECK':
  285. return 'Oozie Service Check';
  286. case 'PIG':
  287. return 'Pig';
  288. case 'PIG_SERVICE_CHECK':
  289. return 'Pig Service Check';
  290. case 'MAPREDUCE2_SERVICE_CHECK':
  291. return 'MapReduce2 Service Check';
  292. case 'YARN_SERVICE_CHECK':
  293. return 'YARN Service Check';
  294. case 'SQOOP':
  295. return 'Sqoop';
  296. case 'SQOOP_SERVICE_CHECK':
  297. return 'Sqoop Service Check';
  298. case 'WEBHCAT_SERVER':
  299. return 'WebHCat Server';
  300. case 'WEBHCAT_SERVICE_CHECK':
  301. return 'WebHCat Service Check';
  302. case 'NAGIOS_SERVER':
  303. return 'Nagios Server';
  304. case 'GANGLIA_SERVER':
  305. return 'Ganglia Server';
  306. case 'GANGLIA_MONITOR':
  307. return 'Ganglia Monitor';
  308. case 'GMOND_SERVICE_CHECK':
  309. return 'Gmond Service Check';
  310. case 'GMETAD_SERVICE_CHECK':
  311. return 'Gmetad Service Check';
  312. case 'DECOMMISSION_DATANODE':
  313. return 'Update Exclude File';
  314. case 'HUE_SERVER':
  315. return 'Hue Server';
  316. case 'HCFS_CLIENT':
  317. return 'HCFS Client';
  318. case 'HCFS_SERVICE_CHECK':
  319. return 'HCFS Service Check';
  320. case 'FLUME_SERVER':
  321. return 'Flume Agent';
  322. case 'ZKFC':
  323. return 'ZKFailoverController';
  324. }
  325. },
  326. /**
  327. * PENDING - Not queued yet for a host
  328. * QUEUED - Queued for a host
  329. * IN_PROGRESS - Host reported it is working
  330. * COMPLETED - Host reported success
  331. * FAILED - Failed
  332. * TIMEDOUT - Host did not respond in time
  333. * ABORTED - Operation was abandoned
  334. */
  335. taskStatus:function (_taskStatus) {
  336. return _taskStatus.toLowerCase();
  337. }
  338. };
  339. /**
  340. * wrapper to bootstrap popover
  341. * fix issue when popover stuck on view routing
  342. * @param self
  343. * @param options
  344. */
  345. App.popover = function(self, options) {
  346. self.popover(options);
  347. self.on("remove", function () {
  348. $(this).trigger('mouseleave');
  349. });
  350. }
  351. /**
  352. * wrapper to bootstrap tooltip
  353. * fix issue when tooltip stuck on view routing
  354. * @param self - DOM element
  355. * @param options
  356. */
  357. App.tooltip = function(self, options) {
  358. self.tooltip(options);
  359. self.on("remove", function () {
  360. $(this).trigger('mouseleave');
  361. });
  362. }
  363. /*
  364. * Helper function for bound property helper registration
  365. * @params name {String} - name of helper
  366. * @params view {Em.View} - view
  367. */
  368. App.registerBoundHelper = function(name, view) {
  369. Em.Handlebars.registerHelper(name, function(property, options) {
  370. options.hash.contentBinding = property;
  371. return Em.Handlebars.helpers.view.call(this, view, options);
  372. });
  373. }
  374. /*
  375. * Return singular or plural word based on Em.I18n property key.
  376. *
  377. * Example: {{pluralize hostsCount singular="t:host" plural="t:hosts"}}
  378. */
  379. App.registerBoundHelper('pluralize', Em.View.extend({
  380. tagName: 'span',
  381. template: Em.Handlebars.compile('{{view.wordOut}}'),
  382. wordOut: function() {
  383. var count, singular, plural;
  384. count = this.get('content');
  385. singular = this.get('singular');
  386. plural = this.get('plural');
  387. return this.getWord(count, singular, plural);
  388. }.property('content'),
  389. getWord: function(count, singular, plural) {
  390. singular = this.tDetect(singular);
  391. plural = this.tDetect(plural);
  392. if (singular && plural) {
  393. if (count > 1) {
  394. return plural;
  395. } else {
  396. return singular;
  397. }
  398. }
  399. },
  400. /*
  401. * Detect for Em.I18n.t reference call
  402. * @params word {String}
  403. * return {String}
  404. */
  405. tDetect: function(word) {
  406. var splitted = word.split(':');
  407. if (splitted.length > 1 && splitted[0] == 't') {
  408. return Em.I18n.t(splitted[1]);
  409. } else {
  410. return splitted[0];
  411. }
  412. }
  413. })
  414. )