background_operations_controller.js 12 KB

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