Debian Codegraph @

cylc/flow/parsec/upgrade.py

raw
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 """Support automatic deprecation and obsoletion of parsec config items."""
17
18 import contextlib
19 from logging import DEBUG, WARNING
20
21 from cylc.flow import LOG
22 from cylc.flow.parsec.exceptions import UpgradeError
23 from cylc.flow.parsec.OrderedDict import OrderedDict
24
25
26 class converter:
27 """Create custom config value converters."""
28
29 def __init__(self, callback, descr):
30 self.callback = callback
31 self.descr = descr
32
33 def describe(self):
34 return self.descr
35
36 def convert(self, val):
37 return self.callback(val)
38
39
40 class upgrader:
41 """Handles upgrading of deprecated config values."""
42
43 SITE_CONFIG = 'site config'
44 USER_CONFIG = 'user config'
45
46 DEPR_TEMPLATE = (
47 "Deprecated config items were automatically upgraded. "
48 "Please alter your {} to use the new syntax."
49 )
50 depr_msg = DEPR_TEMPLATE.format('workflow')
51
52 obslt_msg = (
53 "Obsolete config items were automatically deleted. "
54 "Please check your workflow and remove them permanently."
55 )
56
57 def __init__(self, cfg: dict, descr: str, broadcast: bool = False):
58 """Store the config dict to be upgraded if necessary."""
59 self.cfg = cfg
60 self.descr = descr
61 # upgrades must be ordered in case several act on the same item
62 self.upgrades: OrderedDict[str, list[dict]] = OrderedDict()
63 if broadcast:
64 self.depr_msg = self.DEPR_TEMPLATE.format('broadcast')
65 self.obslt_msg = (
66 "Obsolete config items were rejected by the broadcast."
67 )
68
69 def deprecate(
70 self, vn, oldkeys, newkeys=None,
71 cvtr=None, silent=False, is_section=False,
72 ):
73 """Replace a deprecated key from a config
74 Args:
75 vn (str):
76 Version at which this deprecation occurs.
77 oldkeys (list):
78 Path within config to be changed.
79 newkeys (list):
80 New location in the config for the item in "oldkeys".
81 cvtr (cylc.flow.parsec.upgrade.Converter):
82 Converter object containing a conversion function and a
83 description of that function.
84 silent (bool):
85 Set silent mode for this upgrade.
86 is_section (bool):
87 Is a section heading.
88 """
89 if vn not in self.upgrades:
90 self.upgrades[vn] = []
91 if cvtr is None:
92 cvtr = converter(lambda x: x, "value unchanged") # identity
93 self.upgrades[vn].append(
94 {
95 'old': oldkeys, 'new': newkeys, 'cvt': cvtr,
96 'silent': silent, 'is_section': is_section
97 })
98
99 def obsolete(self, vn, oldkeys, silent=False, is_section=False):
100 """Remove an obsolete key from a config
101 Args:
102 vn (str):
103 Version at which this obsoletion occurs.
104 oldkeys (list):
105 Path within config to be removed.
106 silent:
107 Set silent mode for this upgrade.
108 is_section (bool):
109 Is a section heading.
110 """
111 if vn not in self.upgrades:
112 self.upgrades[vn] = []
113 cvtr = converter(lambda x: x, "DELETED (OBSOLETE)") # identity
114 self.upgrades[vn].append(
115 {
116 'old': oldkeys, 'new': None, 'cvt': cvtr, 'silent': silent,
117 'is_section': is_section
118 })
119
120 def get_item(self, keys):
121 item = self.cfg
122 for key in keys:
123 try:
124 item = item[key]
125 except TypeError:
126 raise UpgradeError(
127 f'{self.show_keys(keys[:-1], True)}'
128 f' ("{keys[-2]}" should be a [section] not a setting)'
129 ) from None
130 return item
131
132 def put_item(self, keys, val):
133 item = self.cfg
134 for key in keys[:-1]:
135 if key not in item:
136 item[key] = {}
137 item = item[key]
138 item[keys[-1]] = val
139
140 def del_item(self, keys):
141 item = self.cfg
142 for key in keys[:-1]:
143 item = item[key]
144 del item[keys[-1]]
145
146 @staticmethod
147 def show_keys(keys, is_section):
148 res = ""
149 for key in keys:
150 if key != keys[-1] or is_section:
151 res += f"[{key}]"
152 else:
153 res += key
154 return res
155
156 def expand(self, upg):
157 """Expands __MANY__ items."""
158 if '__MANY__' not in upg['old']:
159 return [upg]
160 if upg['old'].count('__MANY__') > 1:
161 raise UpgradeError(
162 f"Multiple simultaneous __MANY__ not supported: {upg['old']}")
163 exp_upgs = []
164 pre = []
165 post = []
166 many = []
167 okeys = upg['old']
168 for i, k in enumerate(okeys):
169 if k == "__MANY__":
170 pre = okeys[:i]
171 post = okeys[i + 1:]
172 tmp = self.cfg
173 for j in pre:
174 tmp = tmp[j]
175 many = list(tmp.keys())
176 break
177 if not many:
178 exp_upgs.append(upg)
179 else:
180 i = -1
181 nkeys = upg['new']
182 if nkeys is None: # No new keys defined.
183 for m in many:
184 exp_upgs.append({
185 'old': pre + [m] + post,
186 'new': None,
187 'cvt': upg['cvt'],
188 'silent': upg['silent'],
189 'is_section': upg['is_section'],
190 })
191 return exp_upgs
192 npre = []
193 npost = []
194 for k in nkeys:
195 i += 1 # noqa: SIM113 (multiple loops interacting)
196 if k == "__MANY__":
197 npre = nkeys[:i]
198 npost = nkeys[i + 1:]
199 if not npre or not npost:
200 raise UpgradeError('__MANY__ mismatch')
201 for m in many:
202 exp_upgs.append({
203 'old': pre + [m] + post,
204 'new': npre + [m] + npost,
205 'cvt': upg['cvt'],
206 'silent': upg['silent'],
207 'is_section': upg['is_section'],
208 })
209 return exp_upgs
210
211 def upgrade(self):
212 warnings = OrderedDict()
213 deprecations = False
214 obsoletions = False
215 for vn, upgs in self.upgrades.items():
216 for u in upgs:
217 try:
218 exp = self.expand(u)
219 except (KeyError, UpgradeError):
220 continue
221
222 for upg in exp:
223 try:
224 old = self.get_item(upg['old'])
225 except KeyError:
226 # OK: deprecated item not found
227 pass
228 else:
229 msg = self.show_keys(upg['old'], upg['is_section'])
230 if upg['new']:
231 msg += ' -> ' + self.show_keys(upg['new'],
232 upg['is_section'])
233 deprecations = True
234 else:
235 obsoletions = True
236 msg += " - " + upg['cvt'].describe().format(
237 old=old,
238 new=upg['cvt'].convert(old)
239 )
240 if not upg['silent']:
241 warnings.setdefault(vn, [])
242 warnings[vn].append(msg)
243 self.del_item(upg['old'])
244 if upg['new']:
245 # check self.cfg does not already contain a
246 # non-deprecated item matching upg['new']:
247 nval = ""
248 with contextlib.suppress(KeyError):
249 nval = self.get_item(upg['new'])
250 if nval:
251 # Conflicting item exists, with non-null value.
252 raise UpgradeError(
253 'ERROR: Cannot upgrade deprecated '
254 f'item "{msg}" because the upgraded '
255 'item already exists'
256 )
257 self.put_item(upg['new'],
258 upg['cvt'].convert(old))
259 if warnings:
260 if self.descr == self.SITE_CONFIG:
261 # Site level configuration, user cannot easily fix.
262 # Only log at debug level.
263 level = DEBUG
264 else:
265 # User level configuration, user should be able to fix.
266 # Log at warning level.
267 level = WARNING
268 if obsoletions:
269 LOG.log(level, self.obslt_msg)
270 if deprecations:
271 LOG.log(level, self.depr_msg)
272
273 for vn, msgs in warnings.items():
274 for msg in msgs:
275 LOG.log(level, ' * (%s) %s', vn, msg)