Debian Codegraph @

cylc/flow/subprocctx.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 """Extend parsec.validate for Cylc configuration.
17
18 Coerce more value type from string (to time point, duration, xtriggers, etc.).
19 """
20
21 from inspect import Parameter
22 import json
23 from shlex import quote
24 from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union
25
26
27 from cylc.flow.wallclock import get_current_time_string
28
29 if TYPE_CHECKING:
30 from inspect import Signature
31
32
33 def add_kwarg_to_sig(
34 sig: 'Signature', arg_name: str, default: Any
35 ) -> 'Signature':
36 """Return a new signature with a kwarg added."""
37 # Note: added kwarg has to be before **kwargs ("variadic") in the signature
38 positional_or_keyword: List[Parameter] = []
39 variadic: List[Parameter] = []
40 for param in sig.parameters.values():
41 if param.kind == Parameter.VAR_KEYWORD:
42 variadic.append(param)
43 else:
44 positional_or_keyword.append(param)
45 return sig.replace(parameters=[
46 *positional_or_keyword,
47 Parameter(
48 arg_name,
49 kind=Parameter.KEYWORD_ONLY,
50 default=default,
51 ),
52 *variadic,
53 ])
54
55
56 class SubProcContext: # noqa: SIM119 (not really relevant to this case)
57 """Represent the context of an external command to run as a subprocess.
58
59 Attributes:
60 .cmd (list/str):
61 The command to run expressed as a list (or as a str if shell=True
62 is set in cmd_kwargs).
63 .cmd_key (str):
64 A key to identify the type of command. E.g. "jobs-submit".
65 .cmd_kwargs (dict):
66 Extra information about the command. This may contain:
67 env (dict):
68 Specify extra environment variables for command.
69 err (str):
70 Default STDERR content.
71 out (str):
72 Default STDOUT content.
73 ret_code (int):
74 Default return code.
75 shell (boolean):
76 Launch command with "/bin/sh"?
77 stdin_files (list):
78 Files with content to send to command's STDIN.
79 Can be file paths or opened file handles.
80 stdin_str (str):
81 Content to send to command's STDIN.
82 .err (str):
83 Content of the command's STDERR.
84 .host (str):
85 The host Cylc intended to use for this command.
86 .out (str)
87 Content of the command's STDOUT.
88 .ret_code (int):
89 Return code of the command.
90 .timestamp (str):
91 Time string of latest update.
92 .proc_pool_timeout (float):
93 command execution timeout.
94 """
95
96 # Format string for single line output
97 JOB_LOG_FMT_1 = '[%(cmd_key)s %(attr)s] %(mesg)s'
98 # Format string for multi-line output
99 JOB_LOG_FMT_M = '[%(cmd_key)s %(attr)s]\n%(mesg)s'
100
101 def __init__(self, cmd_key, cmd, host='localhost', **cmd_kwargs):
102 self.timestamp = get_current_time_string()
103 self.cmd_key = cmd_key
104 self.cmd = cmd
105 self.cmd_kwargs = cmd_kwargs
106
107 self.err = cmd_kwargs.get('err')
108 self.ret_code = cmd_kwargs.get('ret_code')
109 self.out = cmd_kwargs.get('out')
110 self.host = host
111
112 def __str__(self):
113 ret = ''
114 for attr in 'cmd', 'ret_code', 'out', 'err':
115 value = getattr(self, attr, None)
116 if value is not None and str(value).strip():
117 mesg = ''
118 if attr == 'cmd' and self.cmd_kwargs.get('stdin_files'):
119 mesg += 'cat'
120 for file_path in self.cmd_kwargs.get('stdin_files'):
121 mesg += ' ' + quote(str(file_path))
122 mesg += ' | '
123 if attr == 'cmd' and isinstance(value, list):
124 mesg += ' '.join(quote(item) for item in value)
125 else:
126 mesg = str(value).strip()
127 if attr == 'cmd' and self.cmd_kwargs.get('stdin_str'):
128 mesg += ' <<<%s' % quote(self.cmd_kwargs.get('stdin_str'))
129 if len(mesg.splitlines()) > 1:
130 fmt = self.JOB_LOG_FMT_M
131 else:
132 fmt = self.JOB_LOG_FMT_1
133 if not mesg.endswith('\n'):
134 mesg += '\n'
135 ret += fmt % {
136 'cmd_key': self.cmd_key,
137 'attr': attr,
138 'mesg': mesg}
139 return ret.rstrip()
140
141 def __repr__(self) -> str:
142 return f"<{type(self).__name__} {self.cmd_key}>"
143
144
145 class SubFuncContext(SubProcContext):
146 """Represent the context of a Python function to run as a subprocess.
147
148 Attributes:
149 # See also parent class attributes.
150 .label:
151 function label under [xtriggers] in flow.cylc
152 .func_name:
153 function name
154 .func_args:
155 function positional args
156 .func_kwargs:
157 function keyword args
158 .intvl:
159 function call interval in secs (how often to check the
160 external trigger)
161 .ret_val
162 function return: (satisfied?, result to pass to trigger tasks)
163 """
164
165 DEFAULT_INTVL = 10.0
166
167 def __init__(
168 self,
169 label: str,
170 func_name: str,
171 func_args: List[Any],
172 func_kwargs: Dict[str, Any],
173 intvl: Union[float, str] = DEFAULT_INTVL,
174 mod_name: Optional[str] = None
175 ):
176 """Initialize a function context."""
177 self.label = label
178 self.mod_name = mod_name or func_name
179 self.func_name = func_name
180 self.func_kwargs = func_kwargs
181 self.func_args = func_args
182 try:
183 self.intvl = float(intvl)
184 except (TypeError, ValueError):
185 self.intvl = self.DEFAULT_INTVL
186 self.ret_val: Tuple[
187 bool, Optional[dict]
188 ] = (False, None) # (satisfied, broadcast)
189 super(SubFuncContext, self).__init__(
190 'xtrigger-func', cmd=[], shell=False
191 )
192
193 def update_command(self, workflow_run_dir):
194 """Update the function wrap command after changes."""
195 self.cmd = ['cylc', 'function-run',
196 self.mod_name,
197 self.func_name,
198 json.dumps(self.func_args),
199 json.dumps(self.func_kwargs),
200 workflow_run_dir]
201
202 def get_signature(self) -> str:
203 """Return the function call signature."""
204 skeys = sorted(self.func_kwargs.keys())
205 args = self.func_args + [
206 "%s=%s" % (i, self.func_kwargs[i]) for i in skeys]
207 return "%s(%s)" % (self.func_name, ", ".join([str(a) for a in args]))
208
209 def get_description(self, show_intvl: bool = False) -> str:
210 """Return a complete description of the function."""
211 descr = f"{self.label} = {self.get_signature()}"
212 if show_intvl:
213 descr = f"call interval {self.intvl}s: {descr}"
214 return descr
215
216 def dump(self) -> str:
217 """Output for logging."""
218 return SubProcContext.__str__(self)
219
220 def __str__(self) -> str:
221 """
222 >>> str(SubFuncContext('label', 'my_func', [1, 2], {'a': 3}))
223 'my_func(1, 2, a=3):10.0'
224 """
225 return f"{self.get_signature()}:{self.intvl}"
226
227 def __repr__(self) -> str:
228 return f"<{type(self).__name__} {self}>"