step3_controller.js 20 KB

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