|
23 | 23 | from TaskWorker.WorkerExceptions import ConfigException
|
24 | 24 | from TaskWorker.Actions.Recurring.BaseRecurringAction import handleRecurring
|
25 | 25 | from TaskWorker.Actions.Handler import handleResubmit, handleNewTask, handleKill
|
| 26 | +from CRABUtils.TaskUtils import getTasks, updateTaskStatus |
| 27 | +import random |
26 | 28 |
|
27 | 29 | ## NOW placing this here, then to be verified if going into Action.Handler, or TSM
|
28 | 30 | ## The meaning of the elements in the 3-tuples are as follows:
|
@@ -245,6 +247,123 @@ def getRecurringActionInst(self, actionName):
|
245 | 247 | return getattr(mod, actionName)(self.config.TaskWorker.logsDir)
|
246 | 248 |
|
247 | 249 |
|
| 250 | + def _externalScheduling(self, limit): |
| 251 | + """ |
| 252 | + External scheduling method using round-robin algorithm to get tasks |
| 253 | + in waiting status and consider resource utilization for fair share. |
| 254 | + """ |
| 255 | + self.logger.info("Starting external scheduling.") |
| 256 | + |
| 257 | + try: |
| 258 | + # Retrieve tasks with 'WAITING' status |
| 259 | + waiting_tasks = getTasks(crabserver=self.crabserver, status='WAITING', logger=self.logger, limit=limit) |
| 260 | + |
| 261 | + if not waiting_tasks: |
| 262 | + self.logger.info("No tasks in 'WAITING' status found.") |
| 263 | + return [] |
| 264 | + |
| 265 | + # Organize tasks by user |
| 266 | + tasks_by_user = {} |
| 267 | + for task in waiting_tasks: |
| 268 | + user = task['tm_username'] |
| 269 | + if user not in tasks_by_user: |
| 270 | + tasks_by_user[user] = [] |
| 271 | + tasks_by_user[user].append(task) |
| 272 | + |
| 273 | + # Perform round-robin selection among users |
| 274 | + users = list(tasks_by_user.keys()) |
| 275 | + random.shuffle(users) # To ensure fair round-robin each time |
| 276 | + selected_tasks = [] |
| 277 | + |
| 278 | + for user in users: |
| 279 | + user_tasks = tasks_by_user[user] |
| 280 | + selected_tasks.extend(user_tasks[:limit // len(users)]) |
| 281 | + |
| 282 | + # Create and populate task_count dictionary |
| 283 | + task_count = {'selected': {}, 'waiting': {}} |
| 284 | + |
| 285 | + for status, tasks in [('selected', selected_tasks), ('waiting', waiting_tasks)]: |
| 286 | + for task in tasks: |
| 287 | + username = task['tm_username'] |
| 288 | + task_count[status][username] = task_count[status].get(username, 0) + 1 |
| 289 | + |
| 290 | + # Prepare table headers and rows |
| 291 | + headers = ['Username', 'Waiting', 'Selected'] |
| 292 | + rows = [] |
| 293 | + |
| 294 | + # Collect all usernames to ensure every user appears in the table |
| 295 | + all_usernames = set(task_count['selected'].keys()).union(task_count['waiting'].keys()) |
| 296 | + |
| 297 | + for username in all_usernames: |
| 298 | + waiting_count = task_count['waiting'].get(username, 0) |
| 299 | + selected_count = task_count['selected'].get(username, 0) |
| 300 | + rows.append([username, waiting_count, selected_count]) |
| 301 | + |
| 302 | + # Determine the width of each column for formatting |
| 303 | + widths = [max(len(header) for header in headers)] + [max(len(str(row[i])) for row in rows) for i in range(1, len(headers))] |
| 304 | + |
| 305 | + # Prepare formatted table string |
| 306 | + table_header = ' | '.join(f'{header:<{width}}' for header, width in zip(headers, widths)) |
| 307 | + table_separator = '-|-'.join('-' * width for width in widths) |
| 308 | + table_rows = '\n'.join(' | '.join(f'{str(cell):<{width}}' for cell, width in zip(row, widths)) for row in rows) |
| 309 | + |
| 310 | + # Combine header, separator, and rows into one string |
| 311 | + table = f"{table_header}\n{table_separator}\n{table_rows}" |
| 312 | + |
| 313 | + # Log the formatted table |
| 314 | + self.logger.info('\n%s', table) |
| 315 | + |
| 316 | + if self.config.TaskScheduling.dry_run: |
| 317 | + return selected_tasks #dry_run True (with Task Scheduling) |
| 318 | + else: |
| 319 | + return waiting_tasks #dry_run False (without Task Scheduling) |
| 320 | + |
| 321 | + except Exception as e: |
| 322 | + self.logger.exception("Exception occurred during external scheduling: %s", str(e)) |
| 323 | + return [] |
| 324 | + |
| 325 | + def _pruneTaskQueue(self): |
| 326 | + self.logger.info("Pruning the queue if required...logic tbd") |
| 327 | + |
| 328 | + def _reportQueueStatus(self): |
| 329 | + self.logger.info("Report Queue status... logic tbd") |
| 330 | + |
| 331 | + |
| 332 | + def _selectWork(self, limit): |
| 333 | + """This function calls external scheduling and updates task status for the selected tasks""" |
| 334 | + self.logger.info("Starting work selection process.") |
| 335 | + |
| 336 | + # Call the external scheduling method |
| 337 | + selected_tasks = self._externalScheduling(limit) |
| 338 | + |
| 339 | + if not selected_tasks: |
| 340 | + return False |
| 341 | + |
| 342 | + try: |
| 343 | + # Update the status of each selected task to 'NEW' |
| 344 | + for task in selected_tasks: |
| 345 | + task_name = task['tm_taskname'] |
| 346 | + updateTaskStatus(crabserver=self.crabserver, taskName=task_name, status='NEW', logger=self.logger) |
| 347 | + self.logger.info("Task %s status updated to 'NEW'.", task_name) |
| 348 | + |
| 349 | + # Prune the task queue if necessary |
| 350 | + self._pruneTaskQueue() |
| 351 | + |
| 352 | + # Report queue status |
| 353 | + self._reportQueueStatus() |
| 354 | + |
| 355 | + except HTTPException as hte: |
| 356 | + msg = "HTTP Error during _selectWork: %s\n" % str(hte) |
| 357 | + msg += "HTTP Headers are %s: " % hte.headers |
| 358 | + self.logger.error(msg) |
| 359 | + return False |
| 360 | + |
| 361 | + except Exception: #pylint: disable=broad-except |
| 362 | + self.logger.exception("Server could not process the _selectWork request.") |
| 363 | + return False |
| 364 | + |
| 365 | + return True |
| 366 | + |
248 | 367 | def _lockWork(self, limit, getstatus, setstatus):
|
249 | 368 | """Today this is always returning true, because we do not want the worker to die if
|
250 | 369 | the server endpoint is not avaialable.
|
@@ -400,6 +519,11 @@ def algorithm(self):
|
400 | 519 | self.restartQueuedTasks()
|
401 | 520 | self.logger.debug("Master Worker Starting Main Cycle.")
|
402 | 521 | while not self.STOP:
|
| 522 | + selection_limit = self.config.TaskScheduling.selection_limit |
| 523 | + if not self._selectWork(limit=selection_limit): |
| 524 | + self.logger.warning("Selection of work failed.") |
| 525 | + else: |
| 526 | + self.logger.info("Work selected successfully.") |
403 | 527 | limit = self.slaves.queueableTasks()
|
404 | 528 | if not self._lockWork(limit=limit, getstatus='NEW', setstatus='HOLDING'):
|
405 | 529 | time.sleep(self.config.TaskWorker.polling)
|
|
0 commit comments