step3_controller.js 20 KB

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