| 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 |
"""Manage flow counter and flow metadata.""" |
| 18 |
|
| 19 |
import datetime |
| 20 |
from typing import ( |
| 21 |
TYPE_CHECKING, |
| 22 |
Dict, |
| 23 |
Iterable, |
| 24 |
List, |
| 25 |
Optional, |
| 26 |
Set, |
| 27 |
) |
| 28 |
|
| 29 |
from cylc.flow import LOG |
| 30 |
|
| 31 |
|
| 32 |
if TYPE_CHECKING: |
| 33 |
from cylc.flow.workflow_db_mgr import WorkflowDatabaseManager |
| 34 |
|
| 35 |
FlowNums = Set[int] |
| 36 |
FLOW_NEW = "new" |
| 37 |
FLOW_NONE = "none" |
| 38 |
|
| 39 |
|
| 40 |
def add_flow_opts_for_trigger_and_set(parser): |
| 41 |
"""Add flow options for the trigger and set commands.""" |
| 42 |
parser.add_option( |
| 43 |
"--flow", |
| 44 |
action="append", |
| 45 |
dest="flow", |
| 46 |
metavar=f"INT|{FLOW_NEW}|{FLOW_NONE}", |
| 47 |
default=[], |
| 48 |
help=( |
| 49 |
'Assign affected tasks to specified flows.' # nosec |
| 50 |
# (false positive, this is not an SQL statement Bandit!) |
| 51 |
' By default, active tasks (n=0) stay in their assigned flow(s)' |
| 52 |
' and inactive tasks (n>0) will be assigned to all active flows.' |
| 53 |
' Use this option to manually specify an integer flow to assign' |
| 54 |
' tasks to, e.g, "--flow=2". Use this option multiple times to' |
| 55 |
' select multiple flows.' |
| 56 |
f' Alternatively, use "--flow={FLOW_NEW}" to start a new' |
| 57 |
f' flow, or "--flow={FLOW_NONE}" to trigger an inactive task in' |
| 58 |
' no flows (this means the workflow will not run on from the' |
| 59 |
' triggered task, only works for inactive tasks).' |
| 60 |
) |
| 61 |
) |
| 62 |
|
| 63 |
parser.add_option( |
| 64 |
"--meta", metavar="DESCRIPTION", action="store", |
| 65 |
dest="flow_descr", default=None, |
| 66 |
help=f"description of new flow (with --flow={FLOW_NEW})." |
| 67 |
) |
| 68 |
|
| 69 |
parser.add_option( |
| 70 |
"--wait", action="store_true", default=False, dest="flow_wait", |
| 71 |
help="Wait for merge with current active flows before flowing on." |
| 72 |
" Note you can use 'cylc set --pre=all' to unset a flow-wait." |
| 73 |
) |
| 74 |
|
| 75 |
|
| 76 |
def add_flow_opts_for_remove(parser): |
| 77 |
"""Add flow options for the remove command.""" |
| 78 |
parser.add_option( |
| 79 |
'--flow', |
| 80 |
action='append', |
| 81 |
dest='flow', |
| 82 |
metavar='INT', |
| 83 |
default=[], |
| 84 |
help=( |
| 85 |
"Remove the task(s) from the specified flow." |
| 86 |
" Use this option multiple times to specify multiple flows." |
| 87 |
" By default, the tasks will be removed from all flows." |
| 88 |
), |
| 89 |
) |
| 90 |
|
| 91 |
|
| 92 |
def stringify_flow_nums(flow_nums: Iterable[int]) -> str: |
| 93 |
"""Return the canonical string for a set of flow numbers. |
| 94 |
|
| 95 |
Examples: |
| 96 |
>>> stringify_flow_nums({1}) |
| 97 |
'1' |
| 98 |
|
| 99 |
>>> stringify_flow_nums({3, 1, 2}) |
| 100 |
'1,2,3' |
| 101 |
|
| 102 |
>>> stringify_flow_nums({}) |
| 103 |
'' |
| 104 |
|
| 105 |
""" |
| 106 |
return ','.join(str(i) for i in sorted(flow_nums)) |
| 107 |
|
| 108 |
|
| 109 |
def repr_flow_nums(flow_nums: FlowNums, full: bool = False) -> str: |
| 110 |
"""Return a representation of a set of flow numbers |
| 111 |
|
| 112 |
If `full` is False, return an empty string for flows=1. |
| 113 |
|
| 114 |
Examples: |
| 115 |
>>> repr_flow_nums({}) |
| 116 |
'(flows=none)' |
| 117 |
|
| 118 |
>>> repr_flow_nums({1}) |
| 119 |
'' |
| 120 |
|
| 121 |
>>> repr_flow_nums({1}, full=True) |
| 122 |
'(flows=1)' |
| 123 |
|
| 124 |
>>> repr_flow_nums({1,2,3}) |
| 125 |
'(flows=1,2,3)' |
| 126 |
|
| 127 |
""" |
| 128 |
if not full and flow_nums == {1}: |
| 129 |
return "" |
| 130 |
return f"(flows={stringify_flow_nums(flow_nums) or 'none'})" |
| 131 |
|
| 132 |
|
| 133 |
class FlowMgr: |
| 134 |
"""Logic to manage flow counter and flow metadata.""" |
| 135 |
|
| 136 |
def __init__( |
| 137 |
self, |
| 138 |
db_mgr: "WorkflowDatabaseManager", |
| 139 |
utc: bool = True |
| 140 |
) -> None: |
| 141 |
"""Initialise the flow manager.""" |
| 142 |
self.db_mgr = db_mgr |
| 143 |
self.flows: Dict[int, Dict[str, str]] = {} |
| 144 |
self.counter: int = 0 |
| 145 |
self._timezone = datetime.timezone.utc if utc else None |
| 146 |
|
| 147 |
def cli_to_flow_nums( |
| 148 |
self, |
| 149 |
flow: List[str], |
| 150 |
meta: Optional[str] = None, |
| 151 |
) -> Set[int]: |
| 152 |
"""Convert validated --flow command options to valid int flow numbers. |
| 153 |
|
| 154 |
Args: |
| 155 |
flow: |
| 156 |
Strings: [int,], or [FLOW_NEW], or [FLOW_NONE]. |
| 157 |
meta: |
| 158 |
Flow description, for FLOW_NEW. |
| 159 |
|
| 160 |
Returns: |
| 161 |
Set of int flow nums. Note empty set can mean no-flow (FLOW_NONE); |
| 162 |
or all flows or all active flows (for default empty inputs). |
| 163 |
|
| 164 |
""" |
| 165 |
if flow == [FLOW_NONE]: |
| 166 |
return set() |
| 167 |
|
| 168 |
if flow == [FLOW_NEW]: |
| 169 |
return {self.get_flow(meta=meta)} |
| 170 |
|
| 171 |
return { |
| 172 |
self.get_flow(flow_num=int(n), meta=meta) |
| 173 |
for n in flow |
| 174 |
} |
| 175 |
|
| 176 |
def get_flow( |
| 177 |
self, |
| 178 |
flow_num: Optional[int] = None, |
| 179 |
meta: Optional[str] = None |
| 180 |
) -> int: |
| 181 |
"""Record and return a valid flow number. |
| 182 |
|
| 183 |
If asked for a new flow: |
| 184 |
- increment the automatic counter to find an unused number |
| 185 |
|
| 186 |
If given a flow number: |
| 187 |
- record a new flow if the number is unused |
| 188 |
- or just return it as an existing flow number |
| 189 |
|
| 190 |
The metadata string is only stored if it is a new flow. |
| 191 |
|
| 192 |
""" |
| 193 |
if flow_num is None: |
| 194 |
self.counter += 1 |
| 195 |
while self.counter in self.flows: |
| 196 |
# Skip manually-created out-of-sequence flows. |
| 197 |
self.counter += 1 |
| 198 |
flow_num = self.counter |
| 199 |
|
| 200 |
if flow_num in self.flows: |
| 201 |
if meta is not None: |
| 202 |
LOG.warning( |
| 203 |
f'Ignoring flow metadata "{meta}":' |
| 204 |
f' {flow_num} is not a new flow' |
| 205 |
) |
| 206 |
else: |
| 207 |
# Record a new flow. |
| 208 |
now_sec = datetime.datetime.now(tz=self._timezone).isoformat( |
| 209 |
timespec="seconds" |
| 210 |
) |
| 211 |
meta = meta or "no description" |
| 212 |
self.flows[flow_num] = { |
| 213 |
"description": meta, |
| 214 |
"start_time": now_sec |
| 215 |
} |
| 216 |
LOG.info( |
| 217 |
f"New flow: {flow_num} ({meta}) {now_sec}" |
| 218 |
) |
| 219 |
self.db_mgr.put_insert_workflow_flows( |
| 220 |
flow_num, |
| 221 |
self.flows[flow_num] |
| 222 |
) |
| 223 |
return flow_num |
| 224 |
|
| 225 |
def load_from_db(self, flow_nums: FlowNums) -> None: |
| 226 |
"""Load flow data for scheduler restart. |
| 227 |
|
| 228 |
Sets the flow counter to the max flow number in the DB. |
| 229 |
Loads metadata for selected flows (those in the task pool at startup). |
| 230 |
|
| 231 |
""" |
| 232 |
self.counter = self.db_mgr.pri_dao.select_workflow_flows_max_flow_num() |
| 233 |
self.flows = self.db_mgr.pri_dao.select_workflow_flows(flow_nums) |
| 234 |
self._log() |
| 235 |
|
| 236 |
def _log(self) -> None: |
| 237 |
"""Write current flow info to log.""" |
| 238 |
if not self.flows: |
| 239 |
LOG.info("Flows: (none)") |
| 240 |
return |
| 241 |
|
| 242 |
LOG.info( |
| 243 |
"Flows:\n" + "\n".join( |
| 244 |
( |
| 245 |
f"flow: {f} " |
| 246 |
f"({self.flows[f]['description']}) " |
| 247 |
f"{self.flows[f]['start_time']}" |
| 248 |
) |
| 249 |
for f in self.flows |
| 250 |
) |
| 251 |
) |