| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program is free software: you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation, either version 3 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
|
| 17 |
"""Implement independent limited task queues.""" |
| 18 |
|
| 19 |
from collections import deque |
| 20 |
from contextlib import suppress |
| 21 |
from typing import TYPE_CHECKING, List, Set, Dict, Counter, Any |
| 22 |
|
| 23 |
from cylc.flow.task_queues import TaskQueueManagerBase |
| 24 |
|
| 25 |
if TYPE_CHECKING: |
| 26 |
from cylc.flow.task_proxy import TaskProxy |
| 27 |
|
| 28 |
|
| 29 |
class LimitedTaskQueue: |
| 30 |
"""One task queue with group members and active limit.""" |
| 31 |
|
| 32 |
def __init__(self, limit: int, members: Set[str]) -> None: |
| 33 |
"""Initialize limiter for active tasks.""" |
| 34 |
self.limit = limit # max active tasks |
| 35 |
self.members = members # member task names |
| 36 |
self.deque: deque = deque() |
| 37 |
|
| 38 |
def push_task(self, itask: 'TaskProxy') -> None: |
| 39 |
"""Queue task if in my membership list.""" |
| 40 |
if itask.tdef.name in self.members: |
| 41 |
self.deque.appendleft(itask) |
| 42 |
|
| 43 |
def push_task_if_limited( |
| 44 |
self, itask: 'TaskProxy', active: Counter[str] |
| 45 |
) -> bool: |
| 46 |
"""Queue task if in my membership and the queue limit is reached.""" |
| 47 |
n_active = sum(active[mem] for mem in self.members) |
| 48 |
if ( |
| 49 |
self.limit and n_active >= self.limit |
| 50 |
and itask.tdef.name in self.members |
| 51 |
): |
| 52 |
self.deque.appendleft(itask) |
| 53 |
return True |
| 54 |
return False |
| 55 |
|
| 56 |
def release(self, active: Counter[str]) -> List['TaskProxy']: |
| 57 |
"""Release tasks if below the active limit.""" |
| 58 |
# The "active" argument counts active tasks by name. |
| 59 |
released: List['TaskProxy'] = [] |
| 60 |
held: List['TaskProxy'] = [] |
| 61 |
n_active: int = 0 |
| 62 |
for mem in self.members: |
| 63 |
n_active += active[mem] |
| 64 |
while not self.limit or n_active < self.limit: |
| 65 |
try: |
| 66 |
itask = self.deque.pop() |
| 67 |
except IndexError: |
| 68 |
# deque empty |
| 69 |
break |
| 70 |
if itask.state.is_held: |
| 71 |
held.append(itask) |
| 72 |
else: |
| 73 |
released.append(itask) |
| 74 |
n_active += 1 |
| 75 |
active.update({itask.tdef.name: 1}) |
| 76 |
for itask in held: |
| 77 |
self.deque.appendleft(itask) |
| 78 |
return released |
| 79 |
|
| 80 |
def remove(self, itask: 'TaskProxy') -> bool: |
| 81 |
"""Remove a single task from queue, return True if removed.""" |
| 82 |
try: |
| 83 |
self.deque.remove(itask) |
| 84 |
except ValueError: |
| 85 |
# not a member |
| 86 |
return False |
| 87 |
return True |
| 88 |
|
| 89 |
def adopt(self, orphans: List[str]) -> None: |
| 90 |
"""Add orphan task names to my membership list.""" |
| 91 |
self.members.update(orphans) |
| 92 |
|
| 93 |
|
| 94 |
class IndepQueueManager(TaskQueueManagerBase): |
| 95 |
"""Implement independent limited task queues. |
| 96 |
|
| 97 |
A task can only belong to one queue. Queues release tasks if the number of |
| 98 |
active tasks in its membership list is below its limit, until the limit is |
| 99 |
reached or the queue is empty. |
| 100 |
|
| 101 |
A limit of zero means unlimited. |
| 102 |
|
| 103 |
""" |
| 104 |
Q_DEFAULT = "default" |
| 105 |
|
| 106 |
def __init__(self, |
| 107 |
qconfig: dict, |
| 108 |
all_task_names: List[str], |
| 109 |
descendants: dict |
| 110 |
) -> None: |
| 111 |
|
| 112 |
# Map of queues by name. |
| 113 |
self.queues: Dict[str, LimitedTaskQueue] = {} |
| 114 |
|
| 115 |
# Add all task names to default queue membership list. |
| 116 |
qconfig[self.Q_DEFAULT]['members'] = set(all_task_names) |
| 117 |
|
| 118 |
# Expand family names in membership lists. |
| 119 |
queues: Dict[str, Any] = self._expand_families( |
| 120 |
qconfig, all_task_names, descendants) |
| 121 |
|
| 122 |
# Make the queues independent. |
| 123 |
queues = self._make_indep(queues) |
| 124 |
for name, config in queues.items(): |
| 125 |
self.queues[name] = LimitedTaskQueue( |
| 126 |
config["limit"], config["members"] |
| 127 |
) |
| 128 |
|
| 129 |
def push_task(self, itask: 'TaskProxy') -> None: |
| 130 |
"""Push a task to the appropriate queue.""" |
| 131 |
for queue in self.queues.values(): |
| 132 |
queue.push_task(itask) |
| 133 |
|
| 134 |
def push_task_if_limited( |
| 135 |
self, itask: 'TaskProxy', active: Counter[str] |
| 136 |
) -> bool: |
| 137 |
"""Push a task to its queue only if the queue limit is reached.""" |
| 138 |
return any( |
| 139 |
queue.push_task_if_limited(itask, active) |
| 140 |
for queue in self.queues.values() |
| 141 |
) |
| 142 |
|
| 143 |
def release_tasks(self, active: Counter[str]) -> List['TaskProxy']: |
| 144 |
"""Release tasks up to the queue limits.""" |
| 145 |
released: List['TaskProxy'] = [] |
| 146 |
for queue in self.queues.values(): |
| 147 |
released += queue.release(active) |
| 148 |
return released |
| 149 |
|
| 150 |
def remove_task(self, itask: 'TaskProxy') -> bool: |
| 151 |
"""Try to remove a task from the queues. Return True if done.""" |
| 152 |
return any(queue.remove(itask) for queue in self.queues.values()) |
| 153 |
|
| 154 |
def adopt_tasks(self, orphans: List[str]) -> None: |
| 155 |
"""Adopt orphaned tasks to the default group.""" |
| 156 |
self.queues[self.Q_DEFAULT].adopt(orphans) |
| 157 |
|
| 158 |
def _make_indep(self, in_queues: dict) -> dict: |
| 159 |
"""Make queues independent: each task can belong to one queue only. |
| 160 |
|
| 161 |
If a task is assigned to multiple queues the last assignment takes |
| 162 |
precedence. The "default" queue contains tasks not in another queue. |
| 163 |
|
| 164 |
""" |
| 165 |
queues: Dict[str, Any] = {} |
| 166 |
seen: Dict[str, str] = {} |
| 167 |
for qname, qconfig in in_queues.items(): |
| 168 |
queues[qname] = {} |
| 169 |
queues[qname]["members"] = qconfig["members"] |
| 170 |
queues[qname]["limit"] = qconfig["limit"] |
| 171 |
if qname == self.Q_DEFAULT: |
| 172 |
continue |
| 173 |
for qmem in qconfig["members"]: |
| 174 |
# Remove from default queue |
| 175 |
with suppress(KeyError): |
| 176 |
# may already have been removed |
| 177 |
queues[self.Q_DEFAULT]["members"].remove(qmem) |
| 178 |
if qmem in seen: |
| 179 |
# Override previous queue assignment. |
| 180 |
oldq = seen[qmem] |
| 181 |
queues[oldq]["members"].remove(qmem) |
| 182 |
else: |
| 183 |
queues[qname]["members"].add(qmem) |
| 184 |
seen[qmem] = qname |
| 185 |
return queues |