step3_controller.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 (this.get('content.installOptions.manualInstall') !== true) {
  89. if (!App.db.getBootStatus()) {
  90. this.startBootstrap();
  91. }
  92. } else {
  93. this.set('bootHosts', this.get('hosts'));
  94. if (App.testMode) {
  95. this.get('bootHosts').setEach('bootStatus', 'REGISTERED');
  96. this.get('bootHosts').setEach('cpu', '2');
  97. this.get('bootHosts').setEach('memory', '2000000');
  98. this.getHostInfo();
  99. } else {
  100. this.set('registrationStartedAt', null);
  101. this.get('bootHosts').setEach('bootStatus', 'DONE');
  102. this.startRegistration();
  103. }
  104. }
  105. },
  106. clearStep: function () {
  107. this.set('stopBootstrap', false);
  108. this.hosts.clear();
  109. this.bootHosts.clear();
  110. App.db.setBootStatus(false);
  111. this.set('isSubmitDisabled', true);
  112. this.set('isRetryDisabled', true);
  113. },
  114. loadStep: function () {
  115. console.log("TRACE: Loading step3: Confirm Hosts");
  116. this.set('registrationStartedAt', null);
  117. this.clearStep();
  118. var hosts = this.loadHosts();
  119. // hosts.setEach('bootStatus', 'RUNNING');
  120. this.renderHosts(hosts);
  121. },
  122. /* Loads the hostinfo from localStorage on the insertion of view. It's being called from view */
  123. loadHosts: function () {
  124. var hostInfo = this.get('content.hosts');
  125. var hosts = new Ember.Set();
  126. for (var index in hostInfo) {
  127. hosts.add(hostInfo[index]);
  128. console.log("TRACE: host name is: " + hostInfo[index].name);
  129. }
  130. return hosts;
  131. },
  132. /* Renders the set of passed hosts */
  133. renderHosts: function (hostsInfo) {
  134. var self = this;
  135. hostsInfo.forEach(function (_hostInfo) {
  136. var hostInfo = App.HostInfo.create({
  137. name: _hostInfo.name,
  138. bootStatus: _hostInfo.bootStatus,
  139. isChecked: false
  140. });
  141. console.log('pushing ' + hostInfo.name);
  142. self.hosts.pushObject(hostInfo);
  143. });
  144. },
  145. /**
  146. * Parses and updates the content based on bootstrap API response.
  147. * Returns true if polling should continue (some hosts are in "RUNNING" state); false otherwise
  148. */
  149. parseHostInfo: function (hostsStatusFromServer) {
  150. hostsStatusFromServer.forEach(function (_hostStatus) {
  151. var host = this.get('bootHosts').findProperty('name', _hostStatus.hostName);
  152. // check if hostname extracted from REST API data matches any hostname in content
  153. // also, make sure that bootStatus modified by isHostsRegistered call does not get overwritten
  154. // since these calls are being made in parallel
  155. if (host && !['REGISTERED', 'REGISTERING'].contains(host.get('bootStatus'))) {
  156. host.set('bootStatus', _hostStatus.status);
  157. host.set('bootLog', _hostStatus.log);
  158. }
  159. }, this);
  160. // if the data rendered by REST API has hosts in "RUNNING" state, polling will continue
  161. return this.get('bootHosts').length != 0 && this.get('bootHosts').someProperty('bootStatus', 'RUNNING');
  162. },
  163. /* Returns the current set of visible hosts on view (All, Succeeded, Failed) */
  164. visibleHosts: function () {
  165. var self = this;
  166. if (this.get('category.hostsBootStatus')) {
  167. return this.hosts.filterProperty('bootStatus', self.get('category.hostsBootStatus'));
  168. } else { // if (this.get('category') === 'All Hosts')
  169. return this.hosts;
  170. }
  171. }.property('category', 'hosts.@each.bootStatus'),
  172. removeHosts: function (hosts) {
  173. var self = this;
  174. App.ModalPopup.show({
  175. header: Em.I18n.t('installer.step3.hosts.remove.popup.header'),
  176. onPrimary: function () {
  177. App.router.send('removeHosts', hosts);
  178. self.hosts.removeObjects(hosts);
  179. if (!self.hosts.length) {
  180. self.set('isSubmitDisabled', true);
  181. }
  182. this.hide();
  183. },
  184. body: Em.I18n.t('installer.step3.hosts.remove.popup.body')
  185. });
  186. },
  187. /* Removes a single element on the trash icon click. Called from View */
  188. removeHost: function (hostInfo) {
  189. this.removeHosts([hostInfo]);
  190. },
  191. removeSelectedHosts: function () {
  192. if (!this.get('noHostsSelected')) {
  193. var selectedHosts = this.get('visibleHosts').filterProperty('isChecked', true);
  194. selectedHosts.forEach(function (_hostInfo) {
  195. console.log('Removing: ' + _hostInfo.name);
  196. });
  197. this.removeHosts(selectedHosts);
  198. }
  199. },
  200. retryHost: function (hostInfo) {
  201. this.retryHosts([hostInfo]);
  202. },
  203. retryHosts: function (hosts) {
  204. var bootStrapData = JSON.stringify({'verbose': true, 'sshKey': this.get('content.installOptions.sshKey'), hosts: hosts.mapProperty('name')});
  205. this.numPolls = 0;
  206. if (this.get('content.installOptions.manualInstall') !== true) {
  207. var requestId = App.router.get('installerController').launchBootstrap(bootStrapData);
  208. this.set('content.installOptions.bootRequestId', requestId);
  209. this.set('registrationStartedAt', null);
  210. this.doBootstrap();
  211. } else {
  212. this.set('registrationStartedAt', null);
  213. this.get('bootHosts').setEach('bootStatus', 'DONE');
  214. this.startRegistration();
  215. }
  216. },
  217. retrySelectedHosts: function () {
  218. if (!this.get('isRetryDisabled')) {
  219. this.set('isRetryDisabled', true);
  220. var selectedHosts = this.get('bootHosts').filterProperty('bootStatus', 'FAILED');
  221. selectedHosts.forEach(function (_host) {
  222. _host.set('bootStatus', 'RUNNING');
  223. _host.set('bootLog', 'Retrying ...');
  224. }, this);
  225. this.retryHosts(selectedHosts);
  226. }
  227. },
  228. numPolls: 0,
  229. startBootstrap: function () {
  230. //this.set('isSubmitDisabled', true); //TODO: uncomment after actual hookup
  231. this.numPolls = 0;
  232. this.set('registrationStartedAt', null);
  233. this.set('bootHosts', this.get('hosts'));
  234. this.get('bootHosts').setEach('bootStatus', 'PENDING');
  235. this.doBootstrap();
  236. },
  237. doBootstrap: function () {
  238. if (this.get('stopBootstrap')) {
  239. return;
  240. }
  241. this.numPolls++;
  242. var self = this;
  243. var url = App.testMode ? '/data/wizard/bootstrap/poll_' + this.numPolls + '.json' : App.apiPrefix + '/bootstrap/' + this.get('content.installOptions.bootRequestId');
  244. $.ajax({
  245. type: 'GET',
  246. url: url,
  247. timeout: App.timeout,
  248. success: function (data) {
  249. if (data.hostsStatus !== null) {
  250. // in case of bootstrapping just one host, the server returns an object rather than an array, so
  251. // force into an array
  252. if (!(data.hostsStatus instanceof Array)) {
  253. data.hostsStatus = [ data.hostsStatus ];
  254. }
  255. console.log("TRACE: In success function for the GET bootstrap call");
  256. var keepPolling = self.parseHostInfo(data.hostsStatus);
  257. // Single host : if the only hostname is invalid (data.status == 'ERROR')
  258. // Multiple hosts : if one or more hostnames are invalid
  259. // following check will mark the bootStatus as 'FAILED' for the invalid hostname
  260. if (data.status == 'ERROR' || data.hostsStatus.length != self.get('bootHosts').length) {
  261. var hosts = self.get('bootHosts');
  262. for (var i = 0; i < hosts.length; i++) {
  263. var isValidHost = data.hostsStatus.someProperty('hostName', hosts[i].get('name'));
  264. if (!isValidHost) {
  265. hosts[i].set('bootStatus', 'FAILED');
  266. hosts[i].set('bootLog', 'Registration with the server failed.');
  267. }
  268. }
  269. }
  270. if (data.hostsStatus.someProperty('status', 'DONE') || data.hostsStatus.someProperty('status', 'FAILED')) {
  271. // kicking off registration polls after at least one host has succeeded
  272. self.startRegistration();
  273. }
  274. if (keepPolling) {
  275. window.setTimeout(function () {
  276. self.doBootstrap()
  277. }, 3000);
  278. return;
  279. }
  280. }
  281. },
  282. statusCode: require('data/statusCodes')
  283. }).retry({times: App.maxRetries, timeout: App.timeout}).then(null,
  284. function () {
  285. App.showReloadPopup();
  286. console.log('Bootstrap failed');
  287. }
  288. );
  289. },
  290. /*
  291. stopBootstrap: function () {
  292. console.log('stopBootstrap() called');
  293. Ember.run.later(this, function () {
  294. this.startRegistration();
  295. }, 1000);
  296. },
  297. */
  298. startRegistration: function () {
  299. if (this.get('registrationStartedAt') == null) {
  300. this.set('registrationStartedAt', new Date().getTime());
  301. console.log('registration started at ' + this.get('registrationStartedAt'));
  302. this.isHostsRegistered();
  303. }
  304. },
  305. isHostsRegistered: function () {
  306. if (this.get('stopBootstrap')) {
  307. return;
  308. }
  309. var self = this;
  310. var hosts = this.get('bootHosts');
  311. var url = App.testMode ? '/data/wizard/bootstrap/single_host_registration.json' : App.apiPrefix + '/hosts';
  312. $.ajax({
  313. type: 'GET',
  314. url: url,
  315. timeout: App.timeout,
  316. success: function (data) {
  317. console.log('registration attempt...');
  318. var jsonData = App.testMode ? data : jQuery.parseJSON(data);
  319. if (!jsonData) {
  320. console.log("Error: jsonData is null");
  321. return;
  322. }
  323. // keep polling until all hosts have registered/failed, or registrationTimeout seconds after the last host finished bootstrapping
  324. var stopPolling = true;
  325. hosts.forEach(function (_host, index) {
  326. // Change name of first host for test mode.
  327. if (App.testMode) {
  328. if (index == 0) {
  329. _host.set('name', 'localhost.localdomain');
  330. }
  331. }
  332. // actions to take depending on the host's current bootStatus
  333. // RUNNING - bootstrap is running; leave it alone
  334. // DONE - bootstrap is done; transition to REGISTERING
  335. // REGISTERING - bootstrap is done but has not registered; transition to REGISTERED if host found in polling API result
  336. // REGISTERED - bootstrap and registration is done; leave it alone
  337. // FAILED - either bootstrap or registration failed; leave it alone
  338. console.log(_host.name + ' bootStatus=' + _host.get('bootStatus'));
  339. switch (_host.get('bootStatus')) {
  340. case 'DONE':
  341. _host.set('bootStatus', 'REGISTERING');
  342. _host.set('bootLog', (_host.get('bootLog') != null ? _host.get('bootLog') : '') + '\nRegistering with the server...');
  343. // update registration timestamp so that the timeout is computed from the last host that finished bootstrapping
  344. self.set('registrationStartedAt', new Date().getTime());
  345. stopPolling = false;
  346. break;
  347. case 'REGISTERING':
  348. if (jsonData.items.someProperty('Hosts.host_name', _host.name)) {
  349. console.log(_host.name + ' has been registered');
  350. _host.set('bootStatus', 'REGISTERED');
  351. _host.set('bootLog', (_host.get('bootLog') != null ? _host.get('bootLog') : '') + '\nRegistration with the server succeeded.');
  352. } else {
  353. console.log(_host.name + ' is registering...');
  354. stopPolling = false;
  355. }
  356. break;
  357. case 'RUNNING':
  358. stopPolling = false;
  359. break;
  360. case 'REGISTERED':
  361. case 'FAILED':
  362. default:
  363. break;
  364. }
  365. }, this);
  366. if (stopPolling) {
  367. self.getHostInfo();
  368. } else if (hosts.someProperty('bootStatus', 'RUNNING') || new Date().getTime() - self.get('registrationStartedAt') < self.get('registrationTimeoutSecs') * 1000) {
  369. // we want to keep polling for registration status if any of the hosts are still bootstrapping (so we check for RUNNING).
  370. window.setTimeout(function () {
  371. self.isHostsRegistered();
  372. }, 3000);
  373. } else {
  374. // registration timed out. mark all REGISTERING hosts to FAILED
  375. console.log('registration timed out');
  376. hosts.filterProperty('bootStatus', 'REGISTERING').forEach(function (_host) {
  377. _host.set('bootStatus', 'FAILED');
  378. _host.set('bootLog', (_host.get('bootLog') != null ? _host.get('bootLog') : '') + '\nRegistration with the server failed.');
  379. });
  380. self.getHostInfo();
  381. }
  382. },
  383. statusCode: require('data/statusCodes')
  384. }).retry({times: App.maxRetries, timeout: App.timeout}).then(null, function () {
  385. App.showReloadPopup();
  386. console.log('Error: Getting registered host information from the server');
  387. });
  388. },
  389. registerErrPopup: function (header, message) {
  390. App.ModalPopup.show({
  391. header: header,
  392. secondary: false,
  393. onPrimary: function () {
  394. this.hide();
  395. },
  396. bodyClass: Ember.View.extend({
  397. template: Ember.Handlebars.compile(['<p>{{view.message}}</p>'].join('\n')),
  398. message: message
  399. })
  400. });
  401. },
  402. /**
  403. * Get disk info and cpu count of booted hosts from server
  404. */
  405. getHostInfo: function () {
  406. var self = this;
  407. var kbPerGb = 1024;
  408. var hosts = this.get('bootHosts');
  409. var url = App.testMode ? '/data/wizard/bootstrap/single_host_information.json' : App.apiPrefix + '/hosts?fields=Hosts/total_mem,Hosts/cpu_count,Hosts/disk_info';
  410. var method = 'GET';
  411. $.ajax({
  412. type: 'GET',
  413. url: url,
  414. contentType: 'application/json',
  415. timeout: App.timeout,
  416. success: function (data) {
  417. var jsonData = (App.testMode) ? data : jQuery.parseJSON(data);
  418. hosts.forEach(function (_host) {
  419. var host = (App.testMode) ? jsonData.items[0] : jsonData.items.findProperty('Hosts.host_name', _host.name);
  420. if (App.skipBootstrap) {
  421. _host.cpu = 2;
  422. _host.memory = ((parseInt(2000000))).toFixed(2);
  423. _host.disk_info = [{"mountpoint": "/", "type":"ext4"},{"mountpoint": "/grid/0", "type":"ext4"}, {"mountpoint": "/grid/1", "type":"ext4"}, {"mountpoint": "/grid/2", "type":"ext4"}];
  424. } else if (host) {
  425. _host.cpu = host.Hosts.cpu_count;
  426. _host.memory = ((parseInt(host.Hosts.total_mem))).toFixed(2);
  427. _host.disk_info = host.Hosts.disk_info;
  428. console.log("The value of memory is: " + _host.memory);
  429. }
  430. });
  431. self.set('bootHosts', hosts);
  432. console.log("The value of hosts: " + JSON.stringify(hosts));
  433. self.stopRegistration();
  434. },
  435. error: function () {
  436. console.log('INFO: Getting host information(cpu_count and total_mem) from the server failed');
  437. self.registerErrPopup(Em.I18n.t('installer.step3.hostInformation.popup.header'), Em.I18n.t('installer.step3.hostInformation.popup.body'));
  438. },
  439. statusCode: require('data/statusCodes')
  440. });
  441. },
  442. stopRegistration: function () {
  443. this.set('isSubmitDisabled', !this.get('bootHosts').someProperty('bootStatus', 'REGISTERED'));
  444. this.set('isRetryDisabled', !this.get('bootHosts').someProperty('bootStatus', 'FAILED'));
  445. },
  446. selectCategory: function(event, context){
  447. this.set('category', event.context);
  448. },
  449. submit: function () {
  450. if (!this.get('isSubmitDisabled')) {
  451. this.set('content.hosts', this.get('bootHosts'));
  452. App.router.send('next');
  453. }
  454. },
  455. hostLogPopup: function (event, context) {
  456. var host = event.context;
  457. App.ModalPopup.show({
  458. header: Em.I18n.t('installer.step3.hostLog.popup.header').format(host.get('name')),
  459. secondary: null,
  460. onPrimary: function () {
  461. this.hide();
  462. },
  463. bodyClass: Ember.View.extend({
  464. templateName: require('templates/wizard/step3_host_log_popup'),
  465. host: host,
  466. didInsertElement: function () {
  467. var self = this;
  468. var button = $(this.get('element')).find('.textTrigger');
  469. button.click(function () {
  470. if (self.get('isTextArea')) {
  471. $(this).text('click to highlight');
  472. } else {
  473. $(this).text('press CTRL+C');
  474. }
  475. self.set('isTextArea', !self.get('isTextArea'));
  476. });
  477. $(this.get('element')).find('.content-area').mouseenter(
  478. function () {
  479. var element = $(this);
  480. element.css('border', '1px solid #dcdcdc');
  481. button.css('visibility', 'visible');
  482. }).mouseleave(
  483. function () {
  484. var element = $(this);
  485. element.css('border', 'none');
  486. button.css('visibility', 'hidden');
  487. })
  488. },
  489. isTextArea: false,
  490. textArea: Em.TextArea.extend({
  491. didInsertElement: function () {
  492. var element = $(this.get('element'));
  493. element.width($(this.get('parentView').get('element')).width() - 10);
  494. element.height($(this.get('parentView').get('element')).height());
  495. element.select();
  496. element.css('resize', 'none');
  497. },
  498. readOnly: true,
  499. value: function () {
  500. return this.get('content');
  501. }.property('content')
  502. })
  503. })
  504. });
  505. },
  506. // TODO: dummy button. Remove this after the hook up with actual REST API.
  507. mockBtn: function () {
  508. this.set('isSubmitDisabled', false);
  509. this.hosts.clear();
  510. var hostInfo = this.mockData;
  511. this.renderHosts(hostInfo);
  512. },
  513. pollBtn: function () {
  514. if (this.get('isSubmitDisabled')) {
  515. return;
  516. }
  517. var hosts = this.get('visibleHosts');
  518. var selectedHosts = hosts.filterProperty('isChecked', true);
  519. selectedHosts.forEach(function (_host) {
  520. console.log('Retrying: ' + _host.name);
  521. });
  522. var mockHosts = this.mockRetryData;
  523. mockHosts.forEach(function (_host) {
  524. console.log('Retrying: ' + _host.name);
  525. });
  526. if (this.parseHostInfo(mockHosts, selectedHosts)) {
  527. // this.saveHostInfoToDb();
  528. }
  529. }
  530. });