batch_scheduled_requests.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one or more
  3. * contributor license agreements. See the NOTICE file distributed with this
  4. * work for additional information regarding copyright ownership. The ASF
  5. * licenses this file to you under the Apache License, Version 2.0 (the
  6. * "License"); you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. * License for the specific language governing permissions and limitations under
  15. * the License.
  16. */
  17. var App = require('app');
  18. /**
  19. * Default success callback for ajax-requests in this module
  20. * @type {Function}
  21. */
  22. var defaultSuccessCallback = function(data, ajaxOptions, params) {
  23. App.router.get('applicationController').dataLoading().done(function(initValue) {
  24. params.query && params.query.set('status', 'SUCCESS');
  25. if (initValue) {
  26. App.router.get('backgroundOperationsController').showPopup();
  27. }
  28. });
  29. };
  30. /**
  31. * Default error callback for ajax-requests in this module
  32. * @param {Object} xhr
  33. * @param {String} textStatus
  34. * @param {String} error
  35. * @param {Object} opt
  36. * @type {Function}
  37. */
  38. var defaultErrorCallback = function(xhr, textStatus, error, opt, params) {
  39. params.query && params.query.set('status', 'FAIL');
  40. App.ajax.defaultErrorHandler(xhr, opt.url, 'POST', xhr.status);
  41. };
  42. /**
  43. * Contains helpful utilities for handling batch and scheduled requests.
  44. */
  45. module.exports = {
  46. /**
  47. * Some services have components which have a need for rolling restarts. This
  48. * method returns the name of the host-component which supports rolling
  49. * restarts for a service.
  50. * @param {String} serviceName
  51. */
  52. getRollingRestartComponentName: function(serviceName) {
  53. var rollingRestartComponents = {
  54. HDFS: 'DATANODE',
  55. YARN: 'NODEMANAGER',
  56. MAPREDUCE: 'TASKTRACKER',
  57. HBASE: 'HBASE_REGIONSERVER',
  58. STORM: 'SUPERVISOR'
  59. };
  60. return rollingRestartComponents[serviceName] ? rollingRestartComponents[serviceName] : null;
  61. },
  62. /**
  63. * Facade-function for restarting host components of specific service
  64. * @param {String} serviceName for which service hostComponents should be restarted
  65. * @param {bool} staleConfigsOnly restart only hostComponents with <code>staleConfig</code> true
  66. */
  67. restartAllServiceHostComponents: function(serviceName, staleConfigsOnly, query) {
  68. var self = this;
  69. var context = staleConfigsOnly ? Em.I18n.t('rollingrestart.context.allWithStaleConfigsForSelectedService').format(serviceName) : Em.I18n.t('rollingrestart.context.allForSelectedService').format(serviceName);
  70. var services = (serviceName === 'HIVE' && App.Service.find('HCATALOG').get('isLoaded')) ? ['HIVE', 'HCATALOG'] : [serviceName];
  71. this.getComponentsFromServer({
  72. services: services,
  73. staleConfigs: staleConfigsOnly ? staleConfigsOnly : null,
  74. passiveState: 'OFF',
  75. displayParams: ['host_components/HostRoles/component_name']
  76. }, function (data) {
  77. var hostComponents = [];
  78. data.items.forEach(function (host) {
  79. host.host_components.forEach(function (hostComponent) {
  80. hostComponents.push(Em.Object.create({
  81. componentName: hostComponent.HostRoles.component_name,
  82. hostName: host.Hosts.host_name
  83. }))
  84. });
  85. });
  86. self.restartHostComponents(hostComponents, context, "SERVICE", query);
  87. });
  88. },
  89. /**
  90. * construct URL from parameters for request in <code>getComponentsFromServer()</code>
  91. * @param options
  92. * @return {String}
  93. */
  94. constructComponentsCallUrl: function (options) {
  95. var multipleValueParams = {
  96. 'services': 'host_components/HostRoles/service_name.in(<entity-names>)',
  97. 'hosts': 'Hosts/host_name.in(<entity-names>)',
  98. 'components': 'host_components/HostRoles/component_name.in(<entity-names>)'
  99. };
  100. var singleValueParams = {
  101. staleConfigs: 'host_components/HostRoles/stale_configs=',
  102. passiveState: 'Hosts/maintenance_state=',
  103. workStatus: 'host_components/HostRoles/state='
  104. };
  105. var displayParams = options.displayParams || [];
  106. var urlParams = '?';
  107. var addAmpersand = false;
  108. for (var i in multipleValueParams) {
  109. var arrayParams = options[i];
  110. if (Array.isArray(arrayParams) && arrayParams.length > 0) {
  111. if (addAmpersand) {
  112. urlParams += '&';
  113. addAmpersand = false;
  114. }
  115. urlParams += multipleValueParams[i].replace('<entity-names>', arrayParams.join(','));
  116. addAmpersand = true;
  117. }
  118. }
  119. for (var j in singleValueParams) {
  120. var param = options[j];
  121. if (!Em.isNone(param)) {
  122. urlParams += (addAmpersand) ? '&' : '';
  123. urlParams += singleValueParams[j] + param.toString();
  124. addAmpersand = true;
  125. }
  126. }
  127. displayParams.forEach(function (displayParam, index, array) {
  128. if (index === 0) {
  129. urlParams += (addAmpersand) ? '&' : '';
  130. urlParams += 'fields=';
  131. }
  132. urlParams += displayParam;
  133. urlParams += (array.length === (index + 1)) ? '' : ",";
  134. });
  135. return urlParams + '&minimal_response=true';
  136. },
  137. /**
  138. * make GET call to server in order to obtain host-components
  139. * which correspond to filter params from <code>options</code>
  140. * @param options
  141. * @param callback
  142. */
  143. getComponentsFromServer: function (options, callback) {
  144. var urlParams = this.constructComponentsCallUrl(options);
  145. App.ajax.send({
  146. name: 'host.host_components.filtered',
  147. sender: this,
  148. data: {
  149. urlParams: urlParams,
  150. callback: callback
  151. },
  152. success: 'getComponentsFromServerSuccessCallback'
  153. });
  154. },
  155. /**
  156. * pass request outcome to <code>callback()<code>
  157. * @param data
  158. * @param opt
  159. * @param params
  160. */
  161. getComponentsFromServerSuccessCallback: function (data, opt, params) {
  162. params.callback(data);
  163. },
  164. /**
  165. * Restart list of host components
  166. * @param {Ember.Enumerable} hostComponentsList list of host components should be restarted
  167. * @param {String} context message to show in BG popup
  168. * @param {String} level - operation level, can be ("CLUSTER", "SERVICE", "HOST", "HOSTCOMPONENT")
  169. * @param {String} query
  170. */
  171. restartHostComponents: function (hostComponentsList, context, level, query) {
  172. context = context || Em.I18n.t('rollingrestart.context.default');
  173. /**
  174. * Format: {
  175. * 'DATANODE': ['host1', 'host2'],
  176. * 'NAMENODE': ['host1', 'host3']
  177. * ...
  178. * }
  179. */
  180. var componentToHostsMap = {};
  181. var hosts = [];
  182. var componentServiceMap = App.QuickDataMapper.componentServiceMap();
  183. hostComponentsList.forEach(function(hc) {
  184. var hostName = hc.get('hostName');
  185. var componentName = hc.get('componentName');
  186. if (!componentToHostsMap[componentName]) {
  187. componentToHostsMap[componentName] = [];
  188. }
  189. componentToHostsMap[componentName].push(hostName);
  190. hosts.push(hostName);
  191. });
  192. var resource_filters = [];
  193. for (var componentName in componentToHostsMap) {
  194. if (componentToHostsMap.hasOwnProperty(componentName)) {
  195. resource_filters.push({
  196. service_name: componentServiceMap[componentName],
  197. component_name: componentName,
  198. hosts: componentToHostsMap[componentName].join(",")
  199. });
  200. }
  201. }
  202. if (hostComponentsList.length > 0) {
  203. var operation_level = this.getOperationLevelobject(level, hosts.uniq().join(","),
  204. componentServiceMap[hostComponentsList[0].get("componentName")], hostComponentsList[0].get("componentName"));
  205. }
  206. if (resource_filters.length) {
  207. App.ajax.send({
  208. name: 'restart.hostComponents',
  209. sender: {
  210. successCallback: defaultSuccessCallback,
  211. errorCallback: defaultErrorCallback
  212. },
  213. data: {
  214. context: context,
  215. resource_filters: resource_filters,
  216. query: query,
  217. operation_level: operation_level
  218. },
  219. success: 'successCallback',
  220. error: 'errorCallback'
  221. });
  222. }
  223. },
  224. /**
  225. * @param {String} level - operation level name, can be ("CLUSTER", "SERVICE", "HOST", "HOSTCOMPONENT")
  226. * @param {String} hostName get host name or hostNames as String("host1,host2")
  227. * @param {String} serviceName
  228. * @param {String} componentName
  229. * @returns {Object} {{level: *, cluster_name: *}} - operation level object
  230. * @method getOperationLevelobject - create operation level object to be included into ajax query
  231. */
  232. getOperationLevelobject: function(level, hostName, serviceName, componentName) {
  233. var operationLevel = {
  234. "level": level,
  235. "cluster_name": App.get("clusterName")
  236. };
  237. if (level === "HOST") {
  238. operationLevel["host_name"] = hostName;
  239. } else if (level === "SERVICE") {
  240. operationLevel["service_name"] = serviceName;
  241. } else {
  242. operationLevel["host_name"] = hostName;
  243. operationLevel["service_name"] = serviceName;
  244. operationLevel["hostcomponent_name"] = componentName;
  245. }
  246. return operationLevel;
  247. },
  248. /**
  249. * Makes a REST call to the server requesting the rolling restart of the
  250. * provided host components.
  251. * @param {Array} restartHostComponents list of host components should be restarted
  252. * @param {Number} batchSize size of each batch
  253. * @param {Number} intervalTimeSeconds delay between two batches
  254. * @param {Number} tolerateSize task failure tolerance
  255. * @param {callback} successCallback
  256. * @param {callback} errorCallback
  257. */
  258. _doPostBatchRollingRestartRequest: function(restartHostComponents, batchSize, intervalTimeSeconds, tolerateSize, successCallback, errorCallback) {
  259. successCallback = successCallback || defaultSuccessCallback;
  260. errorCallback = errorCallback || defaultErrorCallback;
  261. if (!restartHostComponents.length) {
  262. console.log('No batch rolling restart if no restartHostComponents provided!');
  263. return;
  264. }
  265. App.ajax.send({
  266. name: 'rolling_restart.post',
  267. sender: {
  268. successCallback: successCallback,
  269. errorCallback: errorCallback
  270. },
  271. data: {
  272. intervalTimeSeconds: intervalTimeSeconds,
  273. tolerateSize: tolerateSize,
  274. batches: this.getBatchesForRollingRestartRequest(restartHostComponents, batchSize)
  275. },
  276. success: 'successCallback',
  277. error: 'errorCallback'
  278. });
  279. },
  280. /**
  281. * Create list of batches for rolling restart request
  282. * @param {Array} restartHostComponents list host components should be restarted
  283. * @param {Number} batchSize size of each batch
  284. * @returns {Array} list of batches
  285. */
  286. getBatchesForRollingRestartRequest: function(restartHostComponents, batchSize) {
  287. var hostIndex = 0,
  288. batches = [],
  289. batchCount = Math.ceil(restartHostComponents.length / batchSize),
  290. sampleHostComponent = restartHostComponents.objectAt(0),
  291. componentName = sampleHostComponent.get('componentName'),
  292. serviceName = sampleHostComponent.get('serviceName');
  293. for ( var count = 0; count < batchCount; count++) {
  294. var hostNames = [];
  295. for ( var hc = 0; hc < batchSize && hostIndex < restartHostComponents.length; hc++) {
  296. hostNames.push(restartHostComponents.objectAt(hostIndex++).get('hostName'));
  297. }
  298. if (hostNames.length > 0) {
  299. batches.push({
  300. "order_id" : count + 1,
  301. "type" : "POST",
  302. "uri" : App.apiPrefix + "/clusters/" + App.get('clusterName') + "/requests",
  303. "RequestBodyInfo" : {
  304. "RequestInfo" : {
  305. "context" : "_PARSE_.ROLLING-RESTART." + componentName + "." + (count + 1) + "." + batchCount,
  306. "command" : "RESTART"
  307. },
  308. "Requests/resource_filters": [{
  309. "service_name" : serviceName,
  310. "component_name" : componentName,
  311. "hosts" : hostNames.join(",")
  312. }]
  313. }
  314. });
  315. }
  316. }
  317. return batches;
  318. },
  319. /**
  320. * Launches dialog to handle rolling restarts of host components.
  321. *
  322. * Rolling restart is supported only for components listed in <code>getRollingRestartComponentName</code>
  323. * @see getRollingRestartComponentName
  324. * @param {String} hostComponentName
  325. * Type of host-component to restart across cluster
  326. * (ex: DATANODE)
  327. * @param {bool} staleConfigsOnly
  328. * Pre-select host-components which have stale
  329. * configurations
  330. */
  331. launchHostComponentRollingRestart: function(hostComponentName, serviceName, isMaintenanceModeOn, staleConfigsOnly, skipMaintenance) {
  332. if (App.get('components.rollinRestartAllowed').contains(hostComponentName)) {
  333. this.showRollingRestartPopup(hostComponentName, serviceName, isMaintenanceModeOn, staleConfigsOnly, null, skipMaintenance);
  334. }
  335. else {
  336. this.showWarningRollingRestartPopup(hostComponentName);
  337. }
  338. },
  339. /**
  340. * Show popup with rolling restart dialog
  341. * @param {String} hostComponentName name of the host components that should be restarted
  342. * @param {bool} staleConfigsOnly restart only components with <code>staleConfigs</code> = true
  343. * @param {App.hostComponent[]} hostComponents list of hostComponents that should be restarted (optional).
  344. * Using this parameter will reset hostComponentName
  345. */
  346. showRollingRestartPopup: function(hostComponentName, serviceName, isMaintenanceModeOn, staleConfigsOnly, hostComponents, skipMaintenance) {
  347. hostComponents = hostComponents || [];
  348. var componentDisplayName = App.format.role(hostComponentName);
  349. var self = this;
  350. if (!componentDisplayName) {
  351. componentDisplayName = hostComponentName;
  352. }
  353. var title = Em.I18n.t('rollingrestart.dialog.title').format(componentDisplayName);
  354. var viewExtend = {
  355. staleConfigsOnly : staleConfigsOnly,
  356. hostComponentName : hostComponentName,
  357. skipMaintenance: skipMaintenance,
  358. serviceName: serviceName,
  359. isServiceInMM: isMaintenanceModeOn,
  360. didInsertElement: function () {
  361. var view = this;
  362. this.set('parentView.innerView', this);
  363. if (hostComponents.length) {
  364. view.initialize();
  365. } else {
  366. self.getComponentsFromServer({
  367. components: [hostComponentName],
  368. displayParams: ['host_components/HostRoles/stale_configs', 'Hosts/maintenance_state', 'host_components/HostRoles/maintenance_state'],
  369. staleConfigs: staleConfigsOnly ? staleConfigsOnly : null
  370. }, function (data) {
  371. var wrappedHostComponents = [];
  372. data.items.forEach(function (host) {
  373. host.host_components.forEach(function(hostComponent){
  374. wrappedHostComponents.push(Em.Object.create({
  375. componentName: hostComponent.HostRoles.component_name,
  376. serviceName: App.QuickDataMapper.componentServiceMap()[hostComponent.HostRoles.component_name],
  377. hostName: host.Hosts.host_name,
  378. staleConfigs: hostComponent.HostRoles.stale_configs,
  379. hostPassiveState: host.Hosts.maintenance_state,
  380. passiveState: hostComponent.HostRoles.maintenance_state
  381. }));
  382. });
  383. });
  384. view.set('allHostComponents', wrappedHostComponents);
  385. view.initialize();
  386. });
  387. }
  388. }
  389. };
  390. if (hostComponents.length) {
  391. viewExtend.allHostComponents = hostComponents;
  392. }
  393. App.ModalPopup.show({
  394. header : title,
  395. hostComponentName : hostComponentName,
  396. serviceName: serviceName,
  397. isServiceInMM: isMaintenanceModeOn,
  398. staleConfigsOnly : staleConfigsOnly,
  399. skipMaintenance: skipMaintenance,
  400. innerView : null,
  401. bodyClass : App.RollingRestartView.extend(viewExtend),
  402. classNames : [ 'rolling-restart-popup' ],
  403. primary : Em.I18n.t('rollingrestart.dialog.primary'),
  404. onPrimary : function() {
  405. var dialog = this;
  406. var restartComponents = this.get('innerView.restartHostComponents');
  407. var batchSize = this.get('innerView.batchSize');
  408. var waitTime = this.get('innerView.interBatchWaitTimeSeconds');
  409. var tolerateSize = this.get('innerView.tolerateSize');
  410. self._doPostBatchRollingRestartRequest(restartComponents, batchSize, waitTime, tolerateSize, function(data, ajaxOptions, params) {
  411. dialog.hide();
  412. defaultSuccessCallback(data, ajaxOptions, params);
  413. });
  414. },
  415. updateButtons : function() {
  416. var errors = this.get('innerView.errors');
  417. this.set('disablePrimary', (errors != null && errors.length > 0))
  418. }.observes('innerView.errors')
  419. });
  420. },
  421. /**
  422. * Show warning popup about not supported host components
  423. * @param {String} hostComponentName
  424. */
  425. showWarningRollingRestartPopup: function(hostComponentName) {
  426. var componentDisplayName = App.format.role(hostComponentName);
  427. if (!componentDisplayName) {
  428. componentDisplayName = hostComponentName;
  429. }
  430. var title = Em.I18n.t('rollingrestart.dialog.title').format(componentDisplayName);
  431. var msg = Em.I18n.t('rollingrestart.notsupported.hostComponent').format(componentDisplayName);
  432. console.log(msg);
  433. App.ModalPopup.show({
  434. header : title,
  435. secondary : false,
  436. msg : msg,
  437. bodyClass : Em.View.extend({
  438. template : Em.Handlebars.compile('<div class="alert alert-warning">{{msg}}</div>')
  439. })
  440. });
  441. },
  442. /**
  443. * Warn user that alerts will be updated in few minutes
  444. * @param {String} hostComponentName
  445. */
  446. infoPassiveState: function(passiveState) {
  447. var enabled = passiveState == 'OFF' ? 'enabled' : 'suppressed';
  448. App.ModalPopup.show({
  449. header: Em.I18n.t('common.information'),
  450. secondary: null,
  451. bodyClass: Ember.View.extend({
  452. template: Ember.Handlebars.compile('<p>{{view.message}}</p>'),
  453. message: function() {
  454. return Em.I18n.t('hostPopup.warning.alertsTimeOut').format(passiveState.toLowerCase(), enabled);
  455. }.property()
  456. })
  457. });
  458. },
  459. /**
  460. * Retrieves the latest information about a specific request schedule
  461. * identified by 'requestScheduleId'
  462. *
  463. * @param {Number} requestScheduleId ID of the request schedule to get
  464. * @param {Function} successCallback Called with request_schedule data from server. An
  465. * empty object returned for invalid ID.
  466. * @param {Function} errorCallback Optional error callback. Default behavior is to
  467. * popup default error dialog.
  468. */
  469. getRequestSchedule: function(requestScheduleId, successCallback, errorCallback) {
  470. if (requestScheduleId != null && !isNaN(requestScheduleId) && requestScheduleId > -1) {
  471. errorCallback = errorCallback ? errorCallback : defaultErrorCallback;
  472. App.ajax.send({
  473. name : 'request_schedule.get',
  474. sender : {
  475. successCallbackFunction : function(data) {
  476. successCallback(data);
  477. },
  478. errorCallbackFunction : function(xhr, textStatus, error, opt) {
  479. errorCallback(xhr, textStatus, error, opt);
  480. }
  481. },
  482. data : {
  483. request_schedule_id : requestScheduleId
  484. },
  485. success : 'successCallbackFunction',
  486. error : 'errorCallbackFunction'
  487. });
  488. } else {
  489. successCallback({});
  490. }
  491. },
  492. /**
  493. * Attempts to abort a specific request schedule identified by 'requestScheduleId'
  494. *
  495. * @param {Number} requestScheduleId ID of the request schedule to get
  496. * @param {Function} successCallback Called when request schedule successfully aborted
  497. * @param {Function} errorCallback Optional error callback. Default behavior is to
  498. * popup default error dialog.
  499. */
  500. doAbortRequestSchedule: function(requestScheduleId, successCallback, errorCallback) {
  501. if (requestScheduleId != null && !isNaN(requestScheduleId) && requestScheduleId > -1) {
  502. errorCallback = errorCallback || defaultErrorCallback;
  503. App.ajax.send({
  504. name : 'request_schedule.delete',
  505. sender : {
  506. successCallbackFunction : function(data) {
  507. successCallback(data);
  508. },
  509. errorCallbackFunction : function(xhr, textStatus, error, opt) {
  510. errorCallback(xhr, textStatus, error, opt);
  511. }
  512. },
  513. data : {
  514. request_schedule_id : requestScheduleId
  515. },
  516. success : 'successCallbackFunction',
  517. error : 'errorCallbackFunction'
  518. });
  519. } else {
  520. successCallback({});
  521. }
  522. }
  523. };