background_operations_controller.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 hostsMap = {};
  104. var request = this.get('services').findProperty('id', data.Requests.id);
  105. var previousTaskStatusMap = request.get('previousTaskStatusMap');
  106. var currentTaskStatusMap = {};
  107. data.tasks.forEach(function (task) {
  108. var host = hostsMap[task.Tasks.host_name];
  109. if (host) {
  110. host.logTasks.push(task);
  111. host.isModified = (host.isModified) ? true : previousTaskStatusMap[task.Tasks.id] !== task.Tasks.status;
  112. } else {
  113. hostsMap[task.Tasks.host_name] = {
  114. name: task.Tasks.host_name,
  115. publicName: task.Tasks.host_name,
  116. logTasks: [task],
  117. isModified: previousTaskStatusMap[task.Tasks.id] !== task.Tasks.status
  118. };
  119. }
  120. currentTaskStatusMap[task.Tasks.id] = task.Tasks.status;
  121. }, this);
  122. request.set('previousTaskStatusMap', currentTaskStatusMap);
  123. request.set('hostsMap', hostsMap);
  124. this.set('serviceTimestamp', new Date().getTime());
  125. },
  126. /**
  127. * Update task, with uploading two additional properties: stdout and stderr
  128. * @param data
  129. * @param ajaxQuery
  130. * @param params
  131. */
  132. callBackFilteredByTask: function (data, ajaxQuery, params) {
  133. var request = this.get('services').findProperty('id', data.Tasks.request_id);
  134. var host = request.get('hostsMap')[data.Tasks.host_name];
  135. var task = host.logTasks.findProperty('Tasks.id', data.Tasks.id);
  136. task.Tasks.status = data.Tasks.status;
  137. task.Tasks.stdout = data.Tasks.stdout;
  138. task.Tasks.stderr = data.Tasks.stderr;
  139. this.set('serviceTimestamp', new Date().getTime());
  140. },
  141. /**
  142. * Prepare, received from server, requests for host component popup
  143. * @param data
  144. */
  145. callBackForMostRecent: function (data) {
  146. var runningServices = 0;
  147. var self = this;
  148. var currentRequestIds = [];
  149. data.items.forEach(function (request) {
  150. var rq = self.get("services").findProperty('id', request.Requests.id);
  151. var isRunning = (request.Requests.task_count -
  152. (request.Requests.aborted_task_count + request.Requests.completed_task_count + request.Requests.failed_task_count
  153. + request.Requests.timed_out_task_count - request.Requests.queued_task_count)) > 0;
  154. var requestParams = this.parseRequestContext(request.Requests.request_context);
  155. currentRequestIds.push(request.Requests.id);
  156. if (rq) {
  157. rq.set('progress', Math.ceil(request.Requests.progress_percent));
  158. rq.set('status', request.Requests.request_status);
  159. rq.set('isRunning', isRunning);
  160. } else {
  161. rq = Em.Object.create({
  162. id: request.Requests.id,
  163. name: requestParams.requestContext,
  164. displayName: requestParams.requestContext,
  165. progress: Math.ceil(request.Requests.progress_percent),
  166. status: request.Requests.request_status,
  167. isRunning: isRunning,
  168. hostsMap: {},
  169. tasks: [],
  170. dependentService: requestParams.dependentService,
  171. sourceRequestScheduleId: request.Requests.source_schedule_id,
  172. previousTaskStatusMap: {},
  173. contextCommand: requestParams.contextCommand
  174. });
  175. self.get("services").unshift(rq);
  176. }
  177. runningServices += ~~isRunning;
  178. }, this);
  179. //remove old request if it's absent in API response
  180. self.get('services').forEach(function(service, index, services){
  181. if(!currentRequestIds.contains(service.id)) {
  182. services.splice(index, 1);
  183. }
  184. });
  185. self.set("allOperationsCount", runningServices);
  186. self.set('serviceTimestamp', new Date().getTime());
  187. },
  188. /**
  189. * parse request context and if keyword "_PARSE_" is present then format it
  190. * @param requestContext
  191. * @return {Object}
  192. */
  193. parseRequestContext: function (requestContext) {
  194. var parsedRequestContext;
  195. var service;
  196. var contextCommand;
  197. if (requestContext) {
  198. if (requestContext.indexOf(App.BackgroundOperationsController.CommandContexts.PREFIX) !== -1) {
  199. var contextSplits = requestContext.split('.');
  200. contextCommand = contextSplits[1];
  201. service = contextSplits[2];
  202. switch(contextCommand){
  203. case "STOP":
  204. case "START":
  205. if (service === 'ALL_SERVICES') {
  206. parsedRequestContext = Em.I18n.t("requestInfo." + contextCommand.toLowerCase()).format(Em.I18n.t('common.allServices'));
  207. } else {
  208. parsedRequestContext = Em.I18n.t("requestInfo." + contextCommand.toLowerCase()).format(App.Service.DisplayNames[service]);
  209. }
  210. break;
  211. case "ROLLING-RESTART":
  212. parsedRequestContext = Em.I18n.t("rollingrestart.rest.context").format(App.format.role(service), contextSplits[3], contextSplits[4]);
  213. break;
  214. }
  215. } else {
  216. parsedRequestContext = requestContext;
  217. }
  218. } else {
  219. parsedRequestContext = Em.I18n.t('requestInfo.unspecified');
  220. }
  221. return {
  222. requestContext: parsedRequestContext,
  223. dependentService: service,
  224. contextCommand: contextCommand
  225. }
  226. },
  227. popupView: null,
  228. /**
  229. * Onclick handler for background operations number located right to logo
  230. */
  231. showPopup: function(){
  232. // load the checkbox on footer first, then show popup.
  233. var self = this;
  234. App.router.get('applicationController').dataLoading().done(function (initValue) {
  235. App.updater.immediateRun('requestMostRecent');
  236. if(self.get('popupView') && App.HostPopup.get('isBackgroundOperations')){
  237. self.set ('popupView.isNotShowBgChecked', !initValue);
  238. self.set('popupView.isOpen', true);
  239. $(self.get('popupView.element')).appendTo('#wrapper');
  240. } else {
  241. self.set('popupView', App.HostPopup.initPopup("", self, true));
  242. self.set ('popupView.isNotShowBgChecked', !initValue);
  243. }
  244. });
  245. }
  246. });
  247. /**
  248. * Each background operation has a context in which it operates.
  249. * Generally these contexts are fixed messages. However, we might
  250. * want to associate semantics to this context - like showing, disabling
  251. * buttons when certain operations are in progress.
  252. *
  253. * To make this possible we have command contexts where the context
  254. * is not a human readable string, but a pattern indicating the command
  255. * it is running. When UI shows these, they are translated into human
  256. * readable strings.
  257. *
  258. * General pattern of context names is "_PARSE_.{COMMAND}.{ID}[.{Additional-Data}...]"
  259. */
  260. App.BackgroundOperationsController.CommandContexts = {
  261. PREFIX : "_PARSE_",
  262. /**
  263. * Stops all services
  264. */
  265. STOP_ALL_SERVICES : "_PARSE_.STOP.ALL_SERVICES",
  266. /**
  267. * Starts all services
  268. */
  269. START_ALL_SERVICES : "_PARSE_.START.ALL_SERVICES",
  270. /**
  271. * Starts service indicated by serviceID.
  272. * @param {String} serviceID Parameter {0}. Example: HDFS
  273. */
  274. START_SERVICE : "_PARSE_.START.{0}",
  275. /**
  276. * Stops service indicated by serviceID.
  277. * @param {String} serviceID Parameter {0}. Example: HDFS
  278. */
  279. STOP_SERVICE : "_PARSE_.STOP.{0}",
  280. /**
  281. * Performs rolling restart of componentID in batches.
  282. * This context is the batchNumber batch out of totalBatchCount batches.
  283. * @param {String} componentID Parameter {0}. Example "DATANODE"
  284. * @param {Number} batchNumber Parameter {1}. Batch number of this batch. Example 3.
  285. * @param {Number} totalBatchCount Parameter {2}. Total number of batches. Example 10.
  286. */
  287. ROLLING_RESTART : "_PARSE_.ROLLING-RESTART.{0}.{1}.{2}"
  288. }