batch_scheduled_requests.js 21 KB

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