helper.js 11 KB

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