Debian Codegraph @

cylc/flow/scripts/install.py

raw
1 #!/usr/bin/env python3
2
3 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
4 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 """cylc install [OPTIONS] ARGS
20
21 Install a workflow into ~/cylc-run.
22
23 The workflow can then be started, stopped, and targeted by name.
24
25 Normal installation creates a numbered run directory
26 "~/cylc-run/<workflow-name>/run<number>".
27
28 If a SOURCE_NAME is supplied, Cylc will search for the workflow source in the
29 list of directories given by "global.cylc[install]source dirs", and install
30 the first match. The installed workflow ID will start with SOURCE_NAME,
31 unless --workflow-name is used.
32
33 If a PATH is supplied, Cylc will install the workflow from the source directory
34 given by the path. Relative paths must start with "./" to avoid ambiguity with
35 SOURCE_NAME (i.e. "foo/bar" will be interpreted as a source name, whereas
36 "./foo/bar" will be interpreted as a path). The installed workflow ID will
37 start with the basename of the path, unless --workflow-name is used.
38
39 If no argument is supplied, Cylc will install the workflow from the source
40 in the current working directory.
41
42 A "_cylc-install/source" symlink to the source directory will be created in
43 "~/cylc-run/<workflow-name>". Any files or directories (excluding .git, .svn)
44 from the source directory are copied to the new run directory. A ".service"
45 directory will also be created in the run directory; this is used for server
46 authentication files at runtime.
47
48 Examples:
49 # Install workflow "dogs/fido" from the first match in
50 # `global.cylc[install]source dirs`, e.g. ~/cylc-src/dogs/fido/flow.cylc,
51 # with run directory ~/cylc-run/dogs/fido/run1 (if "run1" already exists,
52 # this will increment)
53 $ cylc install dogs/fido
54
55 # Install $PWD as "rabbit", if $PWD is ~/bunny/rabbit, with
56 # run directory ~/cylc-run/rabbit/run1
57 $ cylc install
58
59 # Install $PWD as "rabbit", if $PWD is ~/bunny/rabbit, with
60 # run directory ~/cylc-run/rabbit (note: no "run1" sub-directory)
61 $ cylc install --no-run-name
62
63 # Install $PWD as "fido", regardless of what $PWD is called, with
64 # run directory ~/cylc-run/fido/run1
65 $ cylc install --workflow-name=fido
66
67 # Install $PWD/bunny/rabbit/ as "rabbit", with run directory
68 # ~/cylc-run/rabbit/run1
69 $ cylc install ./bunny/rabbit
70
71 # Install /home/somewhere/badger as "badger", with run directory
72 # ~/cylc-run/badger/run1
73 $ cylc install /home/somewhere/badger
74
75 # Install $PWD as "cats", if $PWD is ~/cats, with run directory
76 # ~/cylc-run/cats/paws
77 $ cylc install --run-name=paws
78
79 The same workflow can be installed with multiple names; this results in
80 multiple workflow run directories that link to the same workflow definition.
81 """
82
83 from ansimarkup import ansiprint as cprint
84 import asyncio
85 from optparse import Values
86 from pathlib import Path
87 from typing import Any, Dict, Optional, Tuple
88
89 from cylc.flow import LOG
90 from cylc.flow.exceptions import InputError
91 from cylc.flow.loggingutil import CylcLogFormatter, set_timestamps
92 from cylc.flow.option_parsers import (
93 CylcOptionParser as COP,
94 OptionSettings,
95 Options
96 )
97 from cylc.flow.pathutil import (
98 EXPLICIT_RELATIVE_PATH_REGEX,
99 expand_path,
100 get_workflow_run_dir
101 )
102 from cylc.flow.plugins import run_plugins_async
103 from cylc.flow.install import (
104 install_workflow,
105 parse_cli_sym_dirs,
106 search_install_source_dirs,
107 check_deprecation,
108 )
109 from cylc.flow.scripts.scan import (
110 get_pipe,
111 _format_plain,
112 FLOW_STATE_SYMBOLS,
113 FLOW_STATE_CMAP
114 )
115 from cylc.flow.terminal import cli_function
116
117
118 INSTALL_OPTIONS = [
119 OptionSettings(
120 ["--workflow-name", "-n"],
121 help="Install into ~/cylc-run/<WORKFLOW_NAME>/runN ",
122 action="store",
123 metavar="WORKFLOW_NAME",
124 default=None,
125 dest="workflow_name",
126 sources={'install'},
127 ),
128 OptionSettings(
129 ["--symlink-dirs"],
130 help=(
131 "Enter a comma-delimited list, in the form"
132 " 'log=path/to/store, share = $HOME/some/path, ...'."
133 " Use this option to override the global.cylc configuration"
134 " for local symlinks for the run, log, work, share and"
135 " share/cycle directories. Enter"
136 " an empty list '' to skip making localhost symlink dirs."),
137 action="store",
138 dest="symlink_dirs",
139 sources={'install'},
140 ),
141 OptionSettings(
142 ["--run-name", "-r"],
143 help=(
144 "Give the run a custom name instead of automatically"
145 " numbering it."),
146 action="store",
147 metavar="RUN_NAME",
148 default=None,
149 dest="run_name",
150 sources={'install'},
151 ),
152 OptionSettings(
153 ["--no-run-name"],
154 help=(
155 "Install the workflow directly into"
156 " ~/cylc-run/<workflow_name>,"
157 " without an automatic run number or custom run name."),
158 action="store_true",
159 default=False,
160 dest="no_run_name",
161 sources={'install'},
162 ),
163 OptionSettings(
164 ['--no-ping'],
165 help=(
166 "When scanning for active instances of the workflow, "
167 "do not attempt to contact the schedulers to get status."),
168 action='store_true',
169 default=False,
170 dest='no_ping',
171 sources={'install'},
172 )
173 ]
174
175
176 def get_option_parser() -> COP:
177 parser = COP(
178 __doc__,
179 comms=True,
180 argdoc=[
181 COP.optional(
182 ('SOURCE_NAME | PATH',
183 'Workflow source name or path to source directory')
184 )
185 ]
186 )
187
188 options = parser.get_cylc_rose_options() + INSTALL_OPTIONS
189
190 for option in options:
191 parser.add_option(*option.args, **option.kwargs)
192
193 return parser
194
195
196 def get_source_location(path: Optional[str]) -> Path:
197 """Return the workflow source location as an absolute path.
198
199 Note: does not check that the source actually exists.
200 """
201 if path is None:
202 return Path.cwd()
203 path = str(path).strip()
204 expanded_path = Path(expand_path(path))
205 if expanded_path.is_absolute():
206 return expanded_path
207 if EXPLICIT_RELATIVE_PATH_REGEX.match(path):
208 return Path.cwd() / expanded_path
209 return search_install_source_dirs(expanded_path)
210
211
212 async def scan(wf_name: str, ping: bool = True) -> None:
213 """Print any instances of wf_name that are already active."""
214 opts = Values({
215 'name': [f'{wf_name}/*'],
216 'states': {'running', 'paused', 'stopping'},
217 'source': False,
218 'ping': ping, # get status of scanned workflows
219 })
220 active = sorted(
221 [
222 item async for item in get_pipe(
223 opts,
224 None,
225 scan_dir=get_workflow_run_dir(wf_name) # restricted scan
226 )
227 ],
228 key=lambda flow: flow['name']
229 )
230 if active:
231 n = len(active)
232 grammar = (
233 ["s", "are", "them all"]
234 if n > 1 else
235 ["", "is", "it"]
236 )
237 cprint(
238 CylcLogFormatter.COLORS['WARNING'].format(
239 f'NOTE: {n} run%s of "{wf_name}"'
240 ' %s already active:' % tuple(grammar[:2])
241 )
242 )
243 for item in active:
244 if opts.ping:
245 status = item['status']
246 tag = FLOW_STATE_CMAP[status]
247 symbol = f" <{tag}>{FLOW_STATE_SYMBOLS[status]}</{tag}>"
248 else:
249 symbol = " "
250 cprint(symbol, _format_plain(item, opts))
251 pattern = (
252 f"'{wf_name}/*'"
253 if n > 1 else
254 f"{item['name']}"
255 )
256 print(
257 f'You can stop %s with:\n cylc stop {pattern}'
258 '\nSee "cylc stop --help" for options.' % grammar[-1]
259 )
260
261
262 InstallOptions = Options(get_option_parser())
263
264
265 @cli_function(get_option_parser)
266 def main(
267 _parser: COP,
268 opts: 'Values',
269 id_: Optional[str] = None
270 ) -> None:
271 """CLI wrapper."""
272 asyncio.run(install_cli(opts, id_))
273
274
275 async def install_cli(
276 opts: 'Values',
277 id_: Optional[str] = None
278 ) -> Tuple[str, str]:
279 """Install workflow and scan for already-running instances."""
280 wf_name, wf_id = await install(opts, id_)
281 await scan(wf_name, not opts.no_ping)
282 return wf_name, wf_id
283
284
285 async def install(
286 opts: 'Values', id_: Optional[str] = None
287 ) -> Tuple[str, str]:
288 set_timestamps(LOG, opts.log_timestamp and opts.verbosity > 1)
289 if opts.no_run_name and opts.run_name:
290 raise InputError(
291 "options --no-run-name and --run-name are mutually exclusive."
292 )
293 source = get_source_location(id_)
294
295 # Check deprecation to allow plugins to have access to correct flags
296 # for compatibility mode:
297 check_deprecation(source)
298
299 async for _entry_point, _plugin_result in run_plugins_async(
300 'cylc.pre_configure',
301 srcdir=source,
302 opts=opts,
303 ):
304 pass
305
306 cli_symdirs: Optional[Dict[str, Dict[str, Any]]] = None
307 if opts.symlink_dirs == '':
308 cli_symdirs = {}
309 elif opts.symlink_dirs:
310 cli_symdirs = parse_cli_sym_dirs(opts.symlink_dirs)
311
312 source_dir, rundir, workflow_name, workflow_id = install_workflow(
313 source=source,
314 workflow_name=opts.workflow_name,
315 run_name=opts.run_name,
316 no_run_name=opts.no_run_name,
317 cli_symlink_dirs=cli_symdirs
318 )
319
320 async for _entry_point, _plugin_result in run_plugins_async(
321 'cylc.post_install',
322 srcdir=source_dir,
323 opts=opts,
324 rundir=str(rundir),
325 async_block=True,
326 ):
327 pass
328
329 print(f'INSTALLED {workflow_id} from {source_dir}')
330
331 return workflow_name, workflow_id