batch_scheduled_requests.js 21 KB

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