step3_controller.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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 App = require('app');
  19. App.WizardStep3Controller = Em.Controller.extend({
  20. name: 'wizardStep3Controller',
  21. hosts: [],
  22. content: [],
  23. bootHosts: [],
  24. registrationStartedAt: null,
  25. registrationTimeoutSecs: 120,
  26. stopBootstrap: false,
  27. isSubmitDisabled: true,
  28. categoryObject: Em.Object.extend({
  29. hostsCount: function () {
  30. var category = this;
  31. var hosts = this.get('controller.hosts').filter(function(_host) {
  32. if (_host.get('bootStatus') == category.get('hostsBootStatus')) {
  33. return true;
  34. } else if (_host.get('bootStatus') == 'DONE' && category.get('hostsBootStatus') == 'REGISTERING') {
  35. return true;
  36. } else {
  37. return false;
  38. }
  39. }, this);
  40. return hosts.get('length');
  41. }.property('controller.hosts.@each.bootStatus'), // 'hosts.@each.bootStatus'
  42. label: function () {
  43. return "%@ (%@)".fmt(this.get('value'), this.get('hostsCount'));
  44. }.property('value', 'hostsCount')
  45. }),
  46. getCategory: function(field, value){
  47. return this.get('categories').find(function(item){
  48. return item.get(field) == value;
  49. });
  50. },
  51. categories: function () {
  52. var self = this;
  53. self.categoryObject.reopen({
  54. controller: self,
  55. isActive: function(){
  56. return this.get('controller.category') == this;
  57. }.property('controller.category'),
  58. itemClass: function(){
  59. return this.get('isActive') ? 'active' : '';
  60. }.property('isActive')
  61. });
  62. var categories = [
  63. self.categoryObject.create({value: 'All', hostsCount: function () {
  64. return this.get('controller.hosts.length');
  65. }.property('controller.hosts.length') }),
  66. self.categoryObject.create({value: 'Installing', hostsBootStatus: 'RUNNING'}),
  67. self.categoryObject.create({value: 'Registering', hostsBootStatus: 'REGISTERING'}),
  68. self.categoryObject.create({value: 'Success', hostsBootStatus: 'REGISTERED' }),
  69. self.categoryObject.create({value: 'Fail', hostsBootStatus: 'FAILED', last: true })
  70. ];
  71. this.set('category', categories.get('firstObject'));
  72. return categories;
  73. }.property(),
  74. category: false,
  75. allChecked: false,
  76. onAllChecked: function () {
  77. var hosts = this.get('visibleHosts');
  78. hosts.setEach('isChecked', this.get('allChecked'));
  79. }.observes('allChecked'),
  80. noHostsSelected: function () {
  81. return !(this.hosts.someProperty('isChecked', true));
  82. }.property('hosts.@each.isChecked'),
  83. isRetryDisabled: true,
  84. mockData: require('data/mock/step3_hosts'),
  85. mockRetryData: require('data/mock/step3_pollData'),
  86. navigateStep: function () {
  87. this.loadStep();
  88. if(App.testMode){
  89. this.getHostInfo();
  90. }
  91. if (this.get('content.installOptions.manualInstall') !== true) {
  92. if (!App.db.getBootStatus()) {
  93. this.startBootstrap();
  94. }
  95. } else {
  96. this.set('bootHosts', this.get('hosts'));
  97. if (App.testMode) {
  98. this.get('bootHosts').setEach('bootStatus', 'REGISTERED');
  99. this.get('bootHosts').setEach('cpu', '2');
  100. this.get('bootHosts').setEach('memory', '2000000');
  101. } else {
  102. this.set('registrationStartedAt', null);
  103. this.get('bootHosts').setEach('bootStatus', 'DONE');
  104. this.startRegistration();
  105. }
  106. }
  107. },
  108. clearStep: function () {
  109. this.set('stopBootstrap', false);
  110. this.hosts.clear();
  111. this.bootHosts.clear();
  112. App.db.setBootStatus(false);
  113. this.set('isSubmitDisabled', true);
  114. this.set('isRetryDisabled', true);
  115. },
  116. loadStep: function () {
  117. console.log("TRACE: Loading step3: Confirm Hosts");
  118. this.set('registrationStartedAt', null);
  119. this.clearStep();
  120. var hosts = this.loadHosts();
  121. // hosts.setEach('bootStatus', 'RUNNING');
  122. this.renderHosts(hosts);
  123. },
  124. /* Loads the hostinfo from localStorage on the insertion of view. It's being called from view */
  125. loadHosts: function () {
  126. var hostInfo = this.get('content.hosts');
  127. var hosts = new Ember.Set();
  128. for (var index in hostInfo) {
  129. hosts.add(hostInfo[index]);
  130. console.log("TRACE: host name is: " + hostInfo[index].name);
  131. }
  132. return hosts;
  133. },
  134. /* Renders the set of passed hosts */
  135. renderHosts: function (hostsInfo) {
  136. var self = this;
  137. hostsInfo.forEach(function (_hostInfo) {
  138. var hostInfo = App.HostInfo.create({
  139. name: _hostInfo.name,
  140. bootStatus: _hostInfo.bootStatus,
  141. isChecked: false
  142. });
  143. console.log('pushing ' + hostInfo.name);
  144. self.hosts.pushObject(hostInfo);
  145. });
  146. },
  147. /**
  148. * Parses and updates the content based on bootstrap API response.
  149. * Returns true if polling should continue (some hosts are in "RUNNING" state); false otherwise
  150. */
  151. parseHostInfo: function (hostsStatusFromServer) {
  152. hostsStatusFromServer.forEach(function (_hostStatus) {
  153. var host = this.get('bootHosts').findProperty('name', _hostStatus.hostName);
  154. // check if hostname extracted from REST API data matches any hostname in content
  155. // also, make sure that bootStatus modified by isHostsRegistered call does not get overwritten
  156. // since these calls are being made in parallel
  157. if (host && !['REGISTERED', 'REGISTERING'].contains(host.get('bootStatus'))) {
  158. host.set('bootStatus', _hostStatus.status);
  159. host.set('bootLog', _hostStatus.log);
  160. }
  161. }, this);
  162. // if the data rendered by REST API has hosts in "RUNNING" state, polling will continue
  163. return this.get('bootHosts').length != 0 && this.get('bootHosts').someProperty('bootStatus', 'RUNNING');
  164. },
  165. /* Returns the current set of visible hosts on view (All, Succeeded, Failed) */
  166. visibleHosts: function () {
  167. var self = this;
  168. if (this.get('category.hostsBootStatus')) {
  169. return this.hosts.filterProperty('bootStatus', self.get('category.hostsBootStatus'));
  170. } else { // if (this.get('category') === 'All Hosts')
  171. return this.hosts;
  172. }
  173. }.property('category', 'hosts.@each.bootStatus'),
  174. removeHosts: function (hosts) {
  175. var self = this;
  176. App.ModalPopup.show({
  177. header: Em.I18n.t('installer.step3.hosts.remove.popup.header'),
  178. onPrimary: function () {
  179. App.router.send('removeHosts', hosts);
  180. self.hosts.removeObjects(hosts);
  181. if (!self.hosts.length) {
  182. self.set('isSubmitDisabled', true);
  183. }
  184. this.hide();
  185. },
  186. body: Em.I18n.t('installer.step3.hosts.remove.popup.body')
  187. });
  188. },
  189. /* Removes a single element on the trash icon click. Called from View */
  190. removeHost: function (hostInfo) {
  191. this.removeHosts([hostInfo]);
  192. },
  193. removeSelectedHosts: function () {
  194. if (!this.get('noHostsSelected')) {
  195. var selectedHosts = this.get('visibleHosts').filterProperty('isChecked', true);
  196. selectedHosts.forEach(function (_hostInfo) {
  197. console.log('Removing: ' + _hostInfo.name);
  198. });
  199. this.removeHosts(selectedHosts);
  200. }
  201. },
  202. retryHost: function (hostInfo) {
  203. this.retryHosts([hostInfo]);
  204. },
  205. retryHosts: function (hosts) {
  206. var bootStrapData = JSON.stringify({'verbose': true, 'sshKey': this.get('content.installOptions.sshKey'), hosts: hosts.mapProperty('name')});
  207. this.numPolls = 0;
  208. if (this.get('content.installOptions.manualInstall') !== true) {
  209. var requestId = App.router.get('installerController').launchBootstrap(bootStrapData);
  210. this.set('content.installOptions.bootRequestId', requestId);
  211. this.set('registrationStartedAt', null);
  212. this.doBootstrap();
  213. } else {
  214. this.set('registrationStartedAt', null);
  215. this.get('bootHosts').setEach('bootStatus', 'DONE');
  216. this.startRegistration();
  217. }
  218. },
  219. retrySelectedHosts: function () {
  220. //to display all hosts
  221. this.set('category', 'All');
  222. if (!this.get('isRetryDisabled')) {
  223. this.set('isRetryDisabled', true);
  224. var selectedHosts = this.get('bootHosts').filterProperty('bootStatus', 'FAILED');
  225. selectedHosts.forEach(function (_host) {
  226. _host.set('bootStatus', 'RUNNING');
  227. _host.set('bootLog', 'Retrying ...');
  228. }, this);
  229. this.retryHosts(selectedHosts);
  230. }
  231. },
  232. numPolls: 0,
  233. startBootstrap: function () {
  234. //this.set('isSubmitDisabled', true); //TODO: uncomment after actual hookup
  235. this.numPolls = 0;
  236. this.set('registrationStartedAt', null);
  237. this.set('bootHosts', this.get('hosts'));
  238. this.get('bootHosts').setEach('bootStatus', 'PENDING');
  239. this.doBootstrap();
  240. },
  241. isInstallInProgress: function(){
  242. var bootStatuses = this.get('bootHosts').getEach('bootStatus');
  243. if(bootStatuses.length &&
  244. (bootStatuses.contains('REGISTERING') ||
  245. bootStatuses.contains('DONE') ||
  246. bootStatuses.contains('RUNNING') ||
  247. bootStatuses.contains('PENDING'))){
  248. return true;
  249. }
  250. return false;
  251. }.property('bootHosts.@each.bootStatus'),
  252. disablePreviousSteps: function(){
  253. if(this.get('isInstallInProgress')){
  254. App.router.get('installerController').setLowerStepsDisable(3);
  255. this.set('isSubmitDisabled', true);
  256. } else {
  257. App.router.get('installerController.isStepDisabled').findProperty('step', 1).set('value', false);
  258. App.router.get('installerController.isStepDisabled').findProperty('step', 2).set('value', false);
  259. }
  260. }.observes('isInstallInProgress'),
  261. doBootstrap: function () {
  262. if (this.get('stopBootstrap')) {
  263. return;
  264. }
  265. this.numPolls++;
  266. var self = this;
  267. var url = App.testMode ? '/data/wizard/bootstrap/poll_' + this.numPolls + '.json' : App.apiPrefix + '/bootstrap/' + this.get('content.installOptions.bootRequestId');
  268. $.ajax({
  269. type: 'GET',
  270. url: url,
  271. timeout: App.timeout,
  272. success: function (data) {
  273. if (data.hostsStatus !== null) {
  274. // in case of bootstrapping just one host, the server returns an object rather than an array, so
  275. // force into an array
  276. if (!(data.hostsStatus instanceof Array)) {
  277. data.hostsStatus = [ data.hostsStatus ];
  278. }
  279. console.log("TRACE: In success function for the GET bootstrap call");
  280. var keepPolling = self.parseHostInfo(data.hostsStatus);
  281. // Single host : if the only hostname is invalid (data.status == 'ERROR')
  282. // Multiple hosts : if one or more hostnames are invalid
  283. // following check will mark the bootStatus as 'FAILED' for the invalid hostname
  284. if (data.status == 'ERROR' || data.hostsStatus.length != self.get('bootHosts').length) {
  285. var hosts = self.get('bootHosts');
  286. for (var i = 0; i < hosts.length; i++) {
  287. var isValidHost = data.hostsStatus.someProperty('hostName', hosts[i].get('name'));
  288. if(hosts[i].get('bootStatus') !== 'REGISTERED'){
  289. if (!isValidHost) {
  290. hosts[i].set('bootStatus', 'FAILED');
  291. hosts[i].set('bootLog', 'Registration with the server failed.');
  292. }
  293. }
  294. }
  295. }
  296. if (data.hostsStatus.someProperty('status', 'DONE') || data.hostsStatus.someProperty('status', 'FAILED')) {
  297. // kicking off registration polls after at least one host has succeeded
  298. self.startRegistration();
  299. }
  300. if (keepPolling) {
  301. window.setTimeout(function () {
  302. self.doBootstrap()
  303. }, 3000);
  304. return;
  305. }
  306. }
  307. },
  308. statusCode: require('data/statusCodes')
  309. }).retry({times: App.maxRetries, timeout: App.timeout}).then(null,
  310. function () {
  311. App.showReloadPopup();
  312. console.log('Bootstrap failed');
  313. }
  314. );
  315. },
  316. /*
  317. stopBootstrap: function () {
  318. console.log('stopBootstrap() called');
  319. Ember.run.later(this, function () {
  320. this.startRegistration();
  321. }, 1000);
  322. },
  323. */
  324. startRegistration: function () {
  325. if (this.get('registrationStartedAt') == null) {
  326. this.set('registrationStartedAt', new Date().getTime());
  327. console.log('registration started at ' + this.get('registrationStartedAt'));
  328. this.isHostsRegistered();
  329. }
  330. },
  331. isHostsRegistered: function () {
  332. if (this.get('stopBootstrap')) {
  333. return;
  334. }
  335. var self = this;
  336. var hosts = this.get('bootHosts');
  337. var url = App.testMode ? '/data/wizard/bootstrap/single_host_registration.json' : App.apiPrefix + '/hosts';
  338. $.ajax({
  339. type: 'GET',
  340. url: url,
  341. timeout: App.timeout,
  342. success: function (data) {
  343. console.log('registration attempt...');
  344. var jsonData = App.testMode ? data : jQuery.parseJSON(data);
  345. if (!jsonData) {
  346. console.log("Error: jsonData is null");
  347. return;
  348. }
  349. // keep polling until all hosts have registered/failed, or registrationTimeout seconds after the last host finished bootstrapping
  350. var stopPolling = true;
  351. hosts.forEach(function (_host, index) {
  352. // Change name of first host for test mode.
  353. if (App.testMode) {
  354. if (index == 0) {
  355. _host.set('name', 'localhost.localdomain');
  356. }
  357. }
  358. // actions to take depending on the host's current bootStatus
  359. // RUNNING - bootstrap is running; leave it alone
  360. // DONE - bootstrap is done; transition to REGISTERING
  361. // REGISTERING - bootstrap is done but has not registered; transition to REGISTERED if host found in polling API result
  362. // REGISTERED - bootstrap and registration is done; leave it alone
  363. // FAILED - either bootstrap or registration failed; leave it alone
  364. console.log(_host.name + ' bootStatus=' + _host.get('bootStatus'));
  365. switch (_host.get('bootStatus')) {
  366. case 'DONE':
  367. _host.set('bootStatus', 'REGISTERING');
  368. _host.set('bootLog', (_host.get('bootLog') != null ? _host.get('bootLog') : '') + '\nRegistering with the server...');
  369. // update registration timestamp so that the timeout is computed from the last host that finished bootstrapping
  370. self.set('registrationStartedAt', new Date().getTime());
  371. stopPolling = false;
  372. break;
  373. case 'REGISTERING':
  374. if (jsonData.items.someProperty('Hosts.host_name', _host.name)) {
  375. console.log(_host.name + ' has been registered');
  376. _host.set('bootStatus', 'REGISTERED');
  377. _host.set('bootLog', (_host.get('bootLog') != null ? _host.get('bootLog') : '') + '\nRegistration with the server succeeded.');
  378. } else {
  379. console.log(_host.name + ' is registering...');
  380. stopPolling = false;
  381. }
  382. break;
  383. case 'RUNNING':
  384. stopPolling = false;
  385. break;
  386. case 'REGISTERED':
  387. case 'FAILED':
  388. default:
  389. break;
  390. }
  391. }, this);
  392. if (stopPolling) {
  393. self.getHostInfo();
  394. } else if (hosts.someProperty('bootStatus', 'RUNNING') || new Date().getTime() - self.get('registrationStartedAt') < self.get('registrationTimeoutSecs') * 1000) {
  395. // we want to keep polling for registration status if any of the hosts are still bootstrapping (so we check for RUNNING).
  396. window.setTimeout(function () {
  397. self.isHostsRegistered();
  398. }, 3000);
  399. } else {
  400. // registration timed out. mark all REGISTERING hosts to FAILED
  401. console.log('registration timed out');
  402. hosts.filterProperty('bootStatus', 'REGISTERING').forEach(function (_host) {
  403. _host.set('bootStatus', 'FAILED');
  404. _host.set('bootLog', (_host.get('bootLog') != null ? _host.get('bootLog') : '') + '\nRegistration with the server failed.');
  405. });
  406. self.getHostInfo();
  407. }
  408. },
  409. statusCode: require('data/statusCodes')
  410. }).retry({times: App.maxRetries, timeout: App.timeout}).then(null, function () {
  411. App.showReloadPopup();
  412. console.log('Error: Getting registered host information from the server');
  413. });
  414. },
  415. registerErrPopup: function (header, message) {
  416. App.ModalPopup.show({
  417. header: header,
  418. secondary: false,
  419. onPrimary: function () {
  420. this.hide();
  421. },
  422. bodyClass: Ember.View.extend({
  423. template: Ember.Handlebars.compile(['<p>{{view.message}}</p>'].join('\n')),
  424. message: message
  425. })
  426. });
  427. },
  428. /**
  429. * Get disk info and cpu count of booted hosts from server
  430. */
  431. getHostInfo: function () {
  432. var self = this;
  433. var kbPerGb = 1024;
  434. var hosts = this.get('bootHosts');
  435. var url = App.testMode ? '/data/wizard/bootstrap/two_hosts_information.json' : App.apiPrefix + '/hosts?fields=Hosts/total_mem,Hosts/cpu_count,Hosts/disk_info,Hosts/last_agent_env';
  436. var method = 'GET';
  437. $.ajax({
  438. type: 'GET',
  439. url: url,
  440. contentType: 'application/json',
  441. timeout: App.timeout,
  442. success: function (data) {
  443. var jsonData = (App.testMode) ? data : jQuery.parseJSON(data);
  444. self.parseWarnings(jsonData);
  445. hosts.forEach(function (_host) {
  446. var host = (App.testMode) ? jsonData.items[0] : jsonData.items.findProperty('Hosts.host_name', _host.name);
  447. if (App.skipBootstrap) {
  448. _host.cpu = 2;
  449. _host.memory = ((parseInt(2000000))).toFixed(2);
  450. _host.disk_info = [{"mountpoint": "/", "type":"ext4"},{"mountpoint": "/grid/0", "type":"ext4"}, {"mountpoint": "/grid/1", "type":"ext4"}, {"mountpoint": "/grid/2", "type":"ext4"}];
  451. } else if (host) {
  452. _host.cpu = host.Hosts.cpu_count;
  453. _host.memory = ((parseInt(host.Hosts.total_mem))).toFixed(2);
  454. _host.disk_info = host.Hosts.disk_info;
  455. console.log("The value of memory is: " + _host.memory);
  456. }
  457. });
  458. self.set('bootHosts', hosts);
  459. console.log("The value of hosts: " + JSON.stringify(hosts));
  460. self.stopRegistration();
  461. },
  462. error: function () {
  463. console.log('INFO: Getting host information(cpu_count and total_mem) from the server failed');
  464. self.registerErrPopup(Em.I18n.t('installer.step3.hostInformation.popup.header'), Em.I18n.t('installer.step3.hostInformation.popup.body'));
  465. },
  466. statusCode: require('data/statusCodes')
  467. });
  468. },
  469. stopRegistration: function () {
  470. this.set('isSubmitDisabled', !this.get('bootHosts').someProperty('bootStatus', 'REGISTERED'));
  471. this.set('isRetryDisabled', !this.get('bootHosts').someProperty('bootStatus', 'FAILED'));
  472. },
  473. selectCategory: function(event, context){
  474. this.set('category', event.context);
  475. },
  476. submit: function () {
  477. if (!this.get('isSubmitDisabled')) {
  478. this.set('content.hosts', this.get('bootHosts'));
  479. App.router.send('next');
  480. }
  481. },
  482. hostLogPopup: function (event, context) {
  483. var host = event.context;
  484. App.ModalPopup.show({
  485. header: Em.I18n.t('installer.step3.hostLog.popup.header').format(host.get('name')),
  486. secondary: null,
  487. onPrimary: function () {
  488. this.hide();
  489. },
  490. bodyClass: Ember.View.extend({
  491. templateName: require('templates/wizard/step3_host_log_popup'),
  492. host: host,
  493. didInsertElement: function () {
  494. var self = this;
  495. var button = $(this.get('element')).find('.textTrigger');
  496. button.click(function () {
  497. if (self.get('isTextArea')) {
  498. $(this).text('click to highlight');
  499. } else {
  500. $(this).text('press CTRL+C');
  501. }
  502. self.set('isTextArea', !self.get('isTextArea'));
  503. });
  504. $(this.get('element')).find('.content-area').mouseenter(
  505. function () {
  506. var element = $(this);
  507. element.css('border', '1px solid #dcdcdc');
  508. button.css('visibility', 'visible');
  509. }).mouseleave(
  510. function () {
  511. var element = $(this);
  512. element.css('border', 'none');
  513. button.css('visibility', 'hidden');
  514. })
  515. },
  516. isTextArea: false,
  517. textArea: Em.TextArea.extend({
  518. didInsertElement: function () {
  519. var element = $(this.get('element'));
  520. element.width($(this.get('parentView').get('element')).width() - 10);
  521. element.height($(this.get('parentView').get('element')).height());
  522. element.select();
  523. element.css('resize', 'none');
  524. },
  525. readOnly: true,
  526. value: function () {
  527. return this.get('content');
  528. }.property('content')
  529. })
  530. })
  531. });
  532. },
  533. /**
  534. * check warnings from server and put it in parsing
  535. */
  536. rerunChecks: function(){
  537. var self = this;
  538. var url = App.testMode ? '/data/wizard/bootstrap/two_hosts_information.json' : App.apiPrefix + '/hosts?fields=Hosts/last_agent_env';
  539. var currentProgress = 0;
  540. var interval = setInterval(function(){
  541. self.set('checksUpdateProgress', Math.ceil((++currentProgress/60)*100))
  542. }, 1000);
  543. setTimeout(function(){
  544. clearInterval(interval);
  545. $.ajax({
  546. type: 'GET',
  547. url: url,
  548. contentType: 'application/json',
  549. timeout: App.timeout,
  550. success: function (data) {
  551. var jsonData = (App.testMode) ? data : jQuery.parseJSON(data);
  552. self.set('checksUpdateProgress', 100);
  553. self.set('checksUpdateStatus', 'SUCCESS');
  554. self.parseWarnings(jsonData);
  555. },
  556. error: function () {
  557. self.set('checksUpdateProgress', 100);
  558. self.set('checksUpdateStatus', 'FAILED');
  559. console.log('INFO: Getting host information(last_agent_env) from the server failed');
  560. },
  561. statusCode: require('data/statusCodes')
  562. })
  563. }, this.get('warningsTimeInterval'));
  564. },
  565. warnings: [],
  566. warningsTimeInterval: 60000,
  567. /**
  568. * check are hosts have any warnings
  569. */
  570. isHostHaveWarnings: function(){
  571. var isWarning = false;
  572. this.get('warnings').forEach(function(warning){
  573. if(!isWarning && (warning.directoriesFiles.someProperty('isWarn', true) ||
  574. warning.packages.someProperty('isWarn', true) ||
  575. warning.processes.someProperty('isWarn', true))){
  576. isWarning = true;
  577. }
  578. }, this);
  579. return isWarning;
  580. }.property('warnings'),
  581. isWarningsBoxVisible: function(){
  582. return (App.testMode) ? true : !this.get('isSubmitDisabled');
  583. }.property('isSubmitDisabled'),
  584. checksUpdateProgress:0,
  585. checksUpdateStatus: null,
  586. /**
  587. * parse warnings data for each host and total
  588. * @param data
  589. */
  590. parseWarnings: function(data){
  591. var warnings = [];
  592. var totalWarnings = {
  593. hostName: 'All Hosts',
  594. directoriesFiles: [],
  595. packages: [],
  596. processes: []
  597. }
  598. //alphabetical sorting
  599. var sortingFunc = function(a, b){
  600. var a1= a.name, b1= b.name;
  601. if(a1== b1) return 0;
  602. return a1> b1? 1: -1;
  603. }
  604. data.items.forEach(function(host){
  605. var warningsByHost = {
  606. hostName: host.Hosts.host_name,
  607. directoriesFiles: [],
  608. packages: [],
  609. processes: []
  610. };
  611. //render all directories and files for each host
  612. host.Hosts.last_agent_env.paths.forEach(function(path){
  613. var parsedPath = {
  614. name: path.name,
  615. isWarn: (path.type == 'not_exist') ? false : true,
  616. message: (path.type == 'not_exist') ? 'OK' : 'WARN: already exists on host'
  617. }
  618. warningsByHost.directoriesFiles.push(parsedPath);
  619. // parsing total warnings
  620. if(!totalWarnings.directoriesFiles.someProperty('name', parsedPath.name)){
  621. totalWarnings.directoriesFiles.push({
  622. name:parsedPath.name,
  623. isWarn: parsedPath.isWarn,
  624. message: (parsedPath.isWarn) ? 'WARN: already exists on 1 host': 'OK',
  625. warnCount: (parsedPath.isWarn) ? 1 : 0
  626. })
  627. } else if(parsedPath.isWarn){
  628. totalWarnings.directoriesFiles.forEach(function(item, index){
  629. if(item.name == parsedPath.name){
  630. totalWarnings.directoriesFiles[index].isWarn = true;
  631. totalWarnings.directoriesFiles[index].warnCount++;
  632. totalWarnings.directoriesFiles[index].message = 'WARN: already exists on '+ totalWarnings.directoriesFiles[index].warnCount +' hosts';
  633. }
  634. });
  635. }
  636. }, this);
  637. //render all packages for each host
  638. host.Hosts.last_agent_env.rpms.forEach(function(_package){
  639. var parsedPackage = {
  640. name: _package.name,
  641. isWarn: _package.installed,
  642. message: (_package.installed) ? 'WARN: already installed on host' : 'OK'
  643. }
  644. warningsByHost.packages.push(parsedPackage);
  645. // parsing total warnings
  646. if(!totalWarnings.packages.someProperty('name', parsedPackage.name)){
  647. totalWarnings.packages.push({
  648. name:parsedPackage.name,
  649. isWarn: parsedPackage.isWarn,
  650. message: (parsedPackage.isWarn) ? 'WARN: already exists on 1 host': 'OK',
  651. warnCount: (parsedPackage.isWarn) ? 1 : 0
  652. })
  653. } else if(parsedPackage.isWarn){
  654. totalWarnings.packages.forEach(function(item, index){
  655. if(item.name == parsedPackage.name){
  656. totalWarnings.packages[index].isWarn = true;
  657. totalWarnings.packages[index].warnCount++;
  658. totalWarnings.packages[index].message = 'WARN: already exists on '+ totalWarnings.packages[index].warnCount +' hosts';
  659. }
  660. });
  661. }
  662. }, this);
  663. // render all process for each host
  664. host.Hosts.last_agent_env.javaProcs.forEach(function(process){
  665. var parsedProcess = {
  666. user: process.user,
  667. isWarn: process.hadoop,
  668. pid: process.pid,
  669. command: process.command,
  670. shortCommand: (process.command.substr(0, 15)+'...'),
  671. message: (process.hadoop) ? 'WARN: running on host' : 'OK'
  672. }
  673. warningsByHost.processes.push(parsedProcess);
  674. // parsing total warnings
  675. if(!totalWarnings.processes.someProperty('pid', parsedProcess.name)){
  676. totalWarnings.processes.push({
  677. user: process.user,
  678. pid: process.pid,
  679. command: process.command,
  680. shortCommand: (process.command.substr(0, 15)+'...'),
  681. isWarn: parsedProcess.isWarn,
  682. message: (parsedProcess.isWarn) ? 'WARN: running on 1 host': 'OK',
  683. warnCount: (parsedProcess.isWarn) ? 1 : 0
  684. })
  685. } else if(parsedProcess.isWarn){
  686. totalWarnings.processes.forEach(function(item, index){
  687. if(item.pid == parsedProcess.pid){
  688. totalWarnings.processes[index].isWarn = true;
  689. totalWarnings.processes[index].warnCount++;
  690. totalWarnings.processes[index].message = 'WARN: running on '+ totalWarnings.processes[index].warnCount +' hosts';
  691. }
  692. });
  693. }
  694. }, this);
  695. warningsByHost.directoriesFiles.sort(sortingFunc);
  696. warningsByHost.packages.sort(sortingFunc);
  697. warnings.push(warningsByHost);
  698. }, this);
  699. totalWarnings.directoriesFiles.sort(sortingFunc);
  700. totalWarnings.packages.sort(sortingFunc);
  701. warnings.unshift(totalWarnings);
  702. this.set('warnings', warnings);
  703. },
  704. /**
  705. * open popup that contain hosts' warnings
  706. * @param event
  707. */
  708. hostWarningsPopup: function(event){
  709. var self = this;
  710. App.ModalPopup.show({
  711. header: Em.I18n.t('installer.step3.warnings.popup.header'),
  712. secondary: 'Rerun Checks',
  713. primary: 'Close',
  714. onPrimary: function () {
  715. self.set('checksUpdateStatus', null);
  716. this.hide();
  717. },
  718. onClose: function(){
  719. self.set('checksUpdateStatus', null);
  720. this.hide();
  721. },
  722. onSecondary: function() {
  723. self.rerunChecks();
  724. },
  725. footerClass: Ember.View.extend({
  726. template: Ember.Handlebars.compile([
  727. '<div class="update-progress pull-left">',
  728. '{{#if view.isUpdateInProgress}}',
  729. '<div class="progress-info active progress">',
  730. '<div class="bar" {{bindAttr style="view.progressWidth"}}></div></div>',
  731. '{{else}}<label {{bindAttr class="view.updateStatusClass"}}>{{view.updateStatus}}</label>',
  732. '{{/if}}</div>',
  733. '{{#if view.parentView.secondary}}<button type="button" class="btn btn-info" {{bindAttr disabled="view.isUpdateInProgress"}} {{action onSecondary target="view.parentView"}}><i class="icon-repeat"></i>&nbsp;{{view.parentView.secondary}}</button>{{/if}}',
  734. '{{#if view.parentView.primary}}<button type="button" class="btn" {{action onPrimary target="view.parentView"}}>{{view.parentView.primary}}</button>{{/if}}'
  735. ].join('')),
  736. classNames: ['modal-footer', 'host-checks-update'],
  737. progressWidth: function(){
  738. return 'width:'+App.router.get('wizardStep3Controller.checksUpdateProgress')+'%';
  739. }.property('App.router.wizardStep3Controller.checksUpdateProgress'),
  740. isUpdateInProgress: function(){
  741. if((App.router.get('wizardStep3Controller.checksUpdateProgress') > 0) &&
  742. (App.router.get('wizardStep3Controller.checksUpdateProgress') < 100)){
  743. return true;
  744. }
  745. }.property('App.router.wizardStep3Controller.checksUpdateProgress'),
  746. updateStatusClass:function(){
  747. var status = App.router.get('wizardStep3Controller.checksUpdateStatus');
  748. if(status === 'SUCCESS'){
  749. return 'text-success';
  750. } else if(status === 'FAILED'){
  751. return 'text-error';
  752. } else {
  753. return null;
  754. }
  755. }.property('App.router.wizardStep3Controller.checksUpdateStatus'),
  756. updateStatus:function(){
  757. var status = App.router.get('wizardStep3Controller.checksUpdateStatus');
  758. if(status === 'SUCCESS'){
  759. return Em.I18n.t('installer.step3.warnings.updateChecks.success');
  760. } else if(status === 'FAILED'){
  761. return Em.I18n.t('installer.step3.warnings.updateChecks.failed');
  762. } else {
  763. return null;
  764. }
  765. }.property('App.router.wizardStep3Controller.checksUpdateStatus')
  766. }),
  767. bodyClass: Ember.View.extend({
  768. templateName: require('templates/wizard/step3_host_warnings_popup'),
  769. warnings: function(){
  770. return App.router.get('wizardStep3Controller.warnings');
  771. }.property('App.router.wizardStep3Controller.warnings'),
  772. categories: function(){
  773. var categories = this.get('warnings').getEach('hostName');
  774. return categories;
  775. }.property('warnings'),
  776. category: 'All Hosts',
  777. content: function(){
  778. return this.get('warnings').findProperty('hostName', this.get('category'));
  779. }.property('category', 'warnings'),
  780. /**
  781. * generate detailed content to show it in new window
  782. */
  783. contentInDetails: function(){
  784. var content = this.get('content');
  785. var newContent = '';
  786. if(content.hostName == 'All Hosts'){
  787. newContent += '<h4>Warnings across all hosts</h4>';
  788. } else {
  789. newContent += '<h4>Warnings on ' + content.hostName + '</h4>';
  790. }
  791. newContent += '<div>DIRECTORIES AND FILES</div><div>';
  792. content.directoriesFiles.filterProperty('isWarn', true).forEach(function(path){
  793. newContent += path.name + '&nbsp;'
  794. });
  795. if(content.directoriesFiles.filterProperty('isWarn', true).length == 0){
  796. newContent += 'No warnings';
  797. }
  798. newContent += '</div><br/><div>PACKAGES</div><div>';
  799. content.packages.filterProperty('isWarn', true).forEach(function(_package){
  800. newContent += _package.name + '&nbsp;'
  801. });
  802. if(content.packages.filterProperty('isWarn', true).length == 0){
  803. newContent += 'No warnings';
  804. }
  805. newContent += '</div><br/><div>PROCESSES</div><div>';
  806. content.processes.filterProperty('isWarn', true).forEach(function(process, index){
  807. newContent += '(' + content.hostName + ',' + process.pid + ',' + process.user + ')';
  808. newContent += (index != (content.processes.filterProperty('isWarn', true).length-1)) ? ',' : '';
  809. })
  810. if(content.processes.filterProperty('isWarn', true).length == 0){
  811. newContent += 'No warnings';
  812. }
  813. return newContent;
  814. }.property('content'),
  815. /**
  816. * open new browser tab with detailed content
  817. */
  818. openWarningsInDialog: function(){
  819. var newWindow = window.open('', this.get('category')+' warnings');
  820. var newDocument = newWindow.document;
  821. newDocument.write(this.get('contentInDetails'));
  822. newWindow.focus();
  823. }
  824. })
  825. })
  826. },
  827. // TODO: dummy button. Remove this after the hook up with actual REST API.
  828. mockBtn: function () {
  829. this.set('isSubmitDisabled', false);
  830. this.hosts.clear();
  831. var hostInfo = this.mockData;
  832. this.renderHosts(hostInfo);
  833. },
  834. pollBtn: function () {
  835. if (this.get('isSubmitDisabled')) {
  836. return;
  837. }
  838. var hosts = this.get('visibleHosts');
  839. var selectedHosts = hosts.filterProperty('isChecked', true);
  840. selectedHosts.forEach(function (_host) {
  841. console.log('Retrying: ' + _host.name);
  842. });
  843. var mockHosts = this.mockRetryData;
  844. mockHosts.forEach(function (_host) {
  845. console.log('Retrying: ' + _host.name);
  846. });
  847. if (this.parseHostInfo(mockHosts, selectedHosts)) {
  848. // this.saveHostInfoToDb();
  849. }
  850. }
  851. });