background_operations_controller.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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.BackgroundOperationsController = Em.Controller.extend({
  20. name: 'backgroundOperationsController',
  21. /**
  22. * Whether we need to refresh background operations or not
  23. */
  24. isWorking : false,
  25. allOperationsCount : 0,
  26. /**
  27. * For host component popup
  28. */
  29. services:[],
  30. serviceTimestamp: null,
  31. /**
  32. * Possible levels:
  33. * REQUESTS_LIST
  34. * HOSTS_LIST
  35. * TASKS_LIST
  36. * TASK_DETAILS
  37. */
  38. levelInfo: Em.Object.create({
  39. name: 'REQUESTS_LIST',
  40. requestId: null,
  41. taskId: null
  42. }),
  43. /**
  44. * Start polling, when <code>isWorking</code> become true
  45. */
  46. startPolling: function(){
  47. if(this.get('isWorking')){
  48. this.requestMostRecent();
  49. App.updater.run(this, 'requestMostRecent', 'isWorking', App.bgOperationsUpdateInterval);
  50. }
  51. }.observes('isWorking'),
  52. /**
  53. * Get requests data from server
  54. * @param callback
  55. */
  56. requestMostRecent: function (callback) {
  57. var queryParams = this.getQueryParams();
  58. App.ajax.send({
  59. 'name': queryParams.name,
  60. 'sender': this,
  61. 'success': queryParams.successCallback,
  62. 'callback': callback,
  63. 'data': queryParams.data
  64. });
  65. return !this.isInitLoading();
  66. },
  67. /**
  68. * indicate whether data for current level has already been loaded or not
  69. * @return {Boolean}
  70. */
  71. isInitLoading: function () {
  72. var levelInfo = this.get('levelInfo');
  73. var request = this.get('services').findProperty('id', levelInfo.get('requestId'));
  74. if (levelInfo.get('name') === 'HOSTS_LIST') {
  75. return !!(request && App.isEmptyObject(request.get('hostsMap')));
  76. }
  77. return false;
  78. },
  79. /**
  80. * construct params of ajax query regarding displayed level
  81. */
  82. getQueryParams: function () {
  83. var levelInfo = this.get('levelInfo');
  84. var count = App.db.getBGOOperationsCount();
  85. var result = {
  86. name: 'background_operations.get_most_recent',
  87. successCallback: 'callBackForMostRecent',
  88. data: {
  89. 'operationsCount': count
  90. }
  91. };
  92. if (levelInfo.get('name') === 'TASK_DETAILS' && !App.get('testMode')) {
  93. result.name = 'background_operations.get_by_task';
  94. result.successCallback = 'callBackFilteredByTask';
  95. result.data = {
  96. 'taskId': levelInfo.get('taskId'),
  97. 'requestId': levelInfo.get('requestId')
  98. };
  99. } else if (levelInfo.get('name') === 'TASKS_LIST' || levelInfo.get('name') === 'HOSTS_LIST') {
  100. result.name = 'background_operations.get_by_request';
  101. result.successCallback = 'callBackFilteredByRequest';
  102. result.data = {
  103. 'requestId': levelInfo.get('requestId')
  104. };
  105. }
  106. return result;
  107. },
  108. /**
  109. * Push hosts and their tasks to request
  110. * @param data
  111. * @param ajaxQuery
  112. * @param params
  113. */
  114. callBackFilteredByRequest: function (data, ajaxQuery, params) {
  115. var requestId = data.Requests.id;
  116. var requestInputs = data.Requests.inputs;
  117. var request = this.get('services').findProperty('id', requestId);
  118. var hostsMap = {};
  119. var previousTaskStatusMap = request.get('previousTaskStatusMap');
  120. var currentTaskStatusMap = {};
  121. data.tasks.forEach(function (task) {
  122. var host = hostsMap[task.Tasks.host_name];
  123. task.Tasks.request_id = requestId;
  124. task.Tasks.request_inputs = requestInputs;
  125. if (host) {
  126. host.logTasks.push(task);
  127. host.isModified = (host.isModified) ? true : previousTaskStatusMap[task.Tasks.id] !== task.Tasks.status;
  128. } else {
  129. hostsMap[task.Tasks.host_name] = {
  130. name: task.Tasks.host_name,
  131. publicName: task.Tasks.host_name,
  132. logTasks: [task],
  133. isModified: previousTaskStatusMap[task.Tasks.id] !== task.Tasks.status
  134. };
  135. }
  136. currentTaskStatusMap[task.Tasks.id] = task.Tasks.status;
  137. }, this);
  138. /**
  139. * sync up request progress with up to date progress of hosts on Host's list,
  140. * to avoid discrepancies while waiting for response with latest progress of request
  141. * after switching to operation's list
  142. */
  143. if (request.get('isRunning')) {
  144. request.set('progress', App.HostPopup.getProgress(data.tasks));
  145. request.set('status', App.HostPopup.getStatus(data.tasks)[0]);
  146. request.set('isRunning', (request.get('progress') !== 100));
  147. }
  148. request.set('previousTaskStatusMap', currentTaskStatusMap);
  149. request.set('hostsMap', hostsMap);
  150. this.set('serviceTimestamp', App.dateTime());
  151. },
  152. /**
  153. * Update task, with uploading two additional properties: stdout and stderr
  154. * @param data
  155. * @param ajaxQuery
  156. * @param params
  157. */
  158. callBackFilteredByTask: function (data, ajaxQuery, params) {
  159. var request = this.get('services').findProperty('id', data.Tasks.request_id);
  160. var host = request.get('hostsMap')[data.Tasks.host_name];
  161. var task = host.logTasks.findProperty('Tasks.id', data.Tasks.id);
  162. task.Tasks.status = data.Tasks.status;
  163. task.Tasks.stdout = data.Tasks.stdout;
  164. task.Tasks.stderr = data.Tasks.stderr;
  165. task.Tasks.output_log = data.Tasks.output_log;
  166. task.Tasks.error_log = data.Tasks.error_log;
  167. this.set('serviceTimestamp', App.dateTime());
  168. },
  169. /**
  170. * Prepare, received from server, requests for host component popup
  171. * @param data
  172. */
  173. callBackForMostRecent: function (data) {
  174. var runningServices = 0;
  175. var currentRequestIds = [];
  176. var countIssued = App.db.getBGOOperationsCount();
  177. var countGot = data.itemTotal;
  178. data.items.forEach(function (request) {
  179. var rq = this.get("services").findProperty('id', request.Requests.id);
  180. var isRunning = this.isRequestRunning(request);
  181. var requestParams = this.parseRequestContext(request.Requests.request_context);
  182. this.assignScheduleId(request, requestParams);
  183. currentRequestIds.push(request.Requests.id);
  184. if (rq) {
  185. rq.set('progress', Math.floor(request.Requests.progress_percent));
  186. rq.set('status', request.Requests.request_status);
  187. rq.set('isRunning', isRunning);
  188. rq.set('startTime', request.Requests.start_time);
  189. rq.set('endTime', request.Requests.end_time);
  190. } else {
  191. rq = Em.Object.create({
  192. id: request.Requests.id,
  193. name: requestParams.requestContext,
  194. displayName: requestParams.requestContext,
  195. progress: Math.floor(request.Requests.progress_percent),
  196. status: request.Requests.request_status,
  197. isRunning: isRunning,
  198. hostsMap: {},
  199. tasks: [],
  200. startTime: request.Requests.start_time,
  201. endTime: request.Requests.end_time,
  202. dependentService: requestParams.dependentService,
  203. sourceRequestScheduleId: request.Requests.request_schedule && request.Requests.request_schedule.schedule_id,
  204. previousTaskStatusMap: {},
  205. contextCommand: requestParams.contextCommand
  206. });
  207. this.get("services").unshift(rq);
  208. //To sort DESC by request id
  209. this.set("services", this.get("services").sort( function(a,b) { return b.get('id') - a.get('id'); })) ;
  210. }
  211. runningServices += ~~isRunning;
  212. }, this);
  213. this.removeOldRequests(currentRequestIds);
  214. this.set("allOperationsCount", runningServices);
  215. this.set('isShowMoreAvailable', countGot >= countIssued);
  216. this.set('serviceTimestamp', App.dateTime());
  217. },
  218. isShowMoreAvailable: null,
  219. /**
  220. * remove old requests
  221. * as API returns 10, or 20 , or 30 ...etc latest request, the requests that absent in response should be removed
  222. * @param currentRequestIds
  223. */
  224. removeOldRequests: function (currentRequestIds) {
  225. this.get('services').forEach(function (service, index, services) {
  226. if (!currentRequestIds.contains(service.id)) {
  227. services.splice(index, 1);
  228. }
  229. });
  230. },
  231. /**
  232. * identify whether request is running by task counters
  233. * @param request
  234. * @return {Boolean}
  235. */
  236. isRequestRunning: function (request) {
  237. return (request.Requests.task_count -
  238. (request.Requests.aborted_task_count + request.Requests.completed_task_count + request.Requests.failed_task_count
  239. + request.Requests.timed_out_task_count - request.Requests.queued_task_count)) > 0;
  240. },
  241. /**
  242. * identify whether there is only one host in request
  243. * @param inputs
  244. * @return {Boolean}
  245. */
  246. isOneHost: function (inputs) {
  247. if (!inputs) {
  248. return false;
  249. }
  250. inputs = JSON.parse(inputs);
  251. if (inputs && inputs.included_hosts) {
  252. return inputs.included_hosts.split(',').length < 2;
  253. }
  254. return false
  255. },
  256. /**
  257. * assign schedule_id of request to null if it's Recommision operation
  258. * @param request
  259. * @param requestParams
  260. */
  261. assignScheduleId: function (request, requestParams) {
  262. var oneHost = this.isOneHost(request.Requests.inputs);
  263. if (request.Requests.request_schedule && oneHost && /Recommission/.test(requestParams.requestContext)) {
  264. request.Requests.request_schedule.schedule_id = null;
  265. }
  266. },
  267. /**
  268. * parse request context and if keyword "_PARSE_" is present then format it
  269. * @param requestContext
  270. * @return {Object}
  271. */
  272. parseRequestContext: function (requestContext) {
  273. var parsedRequestContext;
  274. var service;
  275. var contextCommand;
  276. if (requestContext) {
  277. if (requestContext.indexOf(App.BackgroundOperationsController.CommandContexts.PREFIX) !== -1) {
  278. var contextSplits = requestContext.split('.');
  279. contextCommand = contextSplits[1];
  280. service = contextSplits[2];
  281. switch(contextCommand){
  282. case "STOP":
  283. case "START":
  284. if (service === 'ALL_SERVICES') {
  285. parsedRequestContext = Em.I18n.t("requestInfo." + contextCommand.toLowerCase()).format(Em.I18n.t('common.allServices'));
  286. } else {
  287. parsedRequestContext = Em.I18n.t("requestInfo." + contextCommand.toLowerCase()).format(App.format.role(service));
  288. }
  289. break;
  290. case "ROLLING-RESTART":
  291. parsedRequestContext = Em.I18n.t("rollingrestart.rest.context").format(App.format.role(service), contextSplits[3], contextSplits[4]);
  292. break;
  293. }
  294. } else {
  295. parsedRequestContext = requestContext;
  296. }
  297. } else {
  298. parsedRequestContext = Em.I18n.t('requestInfo.unspecified');
  299. }
  300. return {
  301. requestContext: parsedRequestContext,
  302. dependentService: service,
  303. contextCommand: contextCommand
  304. }
  305. },
  306. popupView: null,
  307. /**
  308. * Onclick handler for background operations number located right to logo
  309. */
  310. showPopup: function(){
  311. // load the checkbox on footer first, then show popup.
  312. var self = this;
  313. App.router.get('applicationController').dataLoading().done(function (initValue) {
  314. App.updater.immediateRun('requestMostRecent');
  315. if(self.get('popupView') && App.HostPopup.get('isBackgroundOperations')){
  316. self.set ('popupView.isNotShowBgChecked', !initValue);
  317. self.set('popupView.isOpen', true);
  318. $(self.get('popupView.element')).appendTo('#wrapper');
  319. } else {
  320. self.set('popupView', App.HostPopup.initPopup("", self, true));
  321. self.set ('popupView.isNotShowBgChecked', !initValue);
  322. }
  323. });
  324. }
  325. });
  326. /**
  327. * Each background operation has a context in which it operates.
  328. * Generally these contexts are fixed messages. However, we might
  329. * want to associate semantics to this context - like showing, disabling
  330. * buttons when certain operations are in progress.
  331. *
  332. * To make this possible we have command contexts where the context
  333. * is not a human readable string, but a pattern indicating the command
  334. * it is running. When UI shows these, they are translated into human
  335. * readable strings.
  336. *
  337. * General pattern of context names is "_PARSE_.{COMMAND}.{ID}[.{Additional-Data}...]"
  338. */
  339. App.BackgroundOperationsController.CommandContexts = {
  340. PREFIX : "_PARSE_",
  341. /**
  342. * Stops all services
  343. */
  344. STOP_ALL_SERVICES : "_PARSE_.STOP.ALL_SERVICES",
  345. /**
  346. * Starts all services
  347. */
  348. START_ALL_SERVICES : "_PARSE_.START.ALL_SERVICES",
  349. /**
  350. * Starts service indicated by serviceID.
  351. * @param {String} serviceID Parameter {0}. Example: HDFS
  352. */
  353. START_SERVICE : "_PARSE_.START.{0}",
  354. /**
  355. * Stops service indicated by serviceID.
  356. * @param {String} serviceID Parameter {0}. Example: HDFS
  357. */
  358. STOP_SERVICE : "_PARSE_.STOP.{0}",
  359. /**
  360. * Performs rolling restart of componentID in batches.
  361. * This context is the batchNumber batch out of totalBatchCount batches.
  362. * @param {String} componentID Parameter {0}. Example "DATANODE"
  363. * @param {Number} batchNumber Parameter {1}. Batch number of this batch. Example 3.
  364. * @param {Number} totalBatchCount Parameter {2}. Total number of batches. Example 10.
  365. */
  366. ROLLING_RESTART : "_PARSE_.ROLLING-RESTART.{0}.{1}.{2}"
  367. };