Debian Codegraph @

cylc/flow/scripts/clean.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 clean [OPTIONS] ARGS
20
21 Delete a stopped workflow.
22
23 Remove workflow files from the local scheduler filesystem and any remote hosts
24 the workflow was installed on.
25
26 NOTE: this command is intended for workflows installed with `cylc install`. If
27 this is run for a workflow that was instead written directly in ~/cylc-run and
28 not backed up elsewhere, it will be lost.
29
30 It will also remove any symlink directory targets.
31
32 Workflow IDs can be hierarchical, corresponding to the path under ~/cylc-run.
33
34 Examples:
35 # Remove the workflow at ~/cylc-run/foo/bar
36 $ cylc clean foo/bar
37
38 # Remove multiple workflows
39 $ cylc clean one two three
40
41 # Remove the workflow's log directory
42 $ cylc clean foo/bar --rm log
43
44 # Remove the log and work directories
45 $ cylc clean foo/bar --rm log:work
46 # or
47 $ cylc clean foo/bar --rm log --rm work
48
49 # Remove all job log files from the 2020 cycle points
50 $ cylc clean foo/bar --rm 'log/job/2020*'
51
52 # Remove all .csv files
53 $ cylc clean foo/bar --rm '**/*.csv'
54
55 # Only remove the workflow on the local filesystem
56 $ cylc clean foo/bar --local-only
57
58 # Only remove the workflow on remote install targets
59 $ cylc clean foo/bar --remote-only
60 """
61
62 import asyncio
63 from optparse import SUPPRESS_HELP
64 import sys
65 from typing import TYPE_CHECKING, Iterable, List, Tuple
66
67 from metomi.isodatetime.exceptions import ISO8601SyntaxError
68 from metomi.isodatetime.parsers import DurationParser
69
70 from cylc.flow import LOG
71 from cylc.flow.clean import init_clean, get_contained_workflows
72 from cylc.flow.exceptions import CylcError, InputError
73 import cylc.flow.flags
74 from cylc.flow.id_cli import parse_ids_async
75 from cylc.flow.loggingutil import set_timestamps
76 from cylc.flow.option_parsers import (
77 WORKFLOW_ID_MULTI_ARG_DOC,
78 CylcOptionParser as COP,
79 Options,
80 )
81 from cylc.flow.terminal import cli_function, is_terminal
82
83 if TYPE_CHECKING:
84 from optparse import Values
85
86
87 def get_option_parser():
88 parser = COP(
89 __doc__,
90 multiworkflow=True,
91 argdoc=[WORKFLOW_ID_MULTI_ARG_DOC],
92 segregated_log=True,
93 )
94
95 parser.add_option(
96 '--rm', metavar='DIR[:DIR:...]',
97 help=("Only clean the specified subdirectories (or files) in the "
98 "run directory, rather than the whole run directory. "
99 "Accepts quoted globs."),
100 action='append', dest='rm_dirs', default=[]
101 )
102
103 parser.add_option(
104 '--local-only', '--local',
105 help="Only clean on the local filesystem (not remote hosts).",
106 action='store_true', dest='local_only'
107 )
108
109 parser.add_option(
110 '--remote-only', '--remote',
111 help="Only clean on remote hosts (not the local filesystem).",
112 action='store_true', dest='remote_only'
113 )
114
115 parser.add_option(
116 '--yes', '-y',
117 help=(
118 "Skip interactive prompt if trying to clean multiple "
119 "run directories at once."
120 ),
121 action='store_true', dest='skip_interactive'
122 )
123
124 parser.add_option(
125 '--timeout',
126 help=(
127 "The length of time to wait for cleaning to take place on "
128 r"remote hosts before cancelling. Default: %default."
129 ),
130 action='store', default='PT5M', dest='remote_timeout'
131 )
132
133 parser.add_option(
134 '--no-scan',
135 help=SUPPRESS_HELP, action='store_true', dest='no_scan'
136 # Used on remote re-invocation - do not scan for workflows, just
137 # clean exactly what you were told to clean
138 )
139
140 return parser
141
142
143 CleanOptions = Options(get_option_parser())
144
145
146 def parse_timeout(opts: 'Values') -> None:
147 """Parse timeout as ISO 8601 duration or number of seconds."""
148 if opts.remote_timeout:
149 try:
150 timeout = int(
151 DurationParser().parse(opts.remote_timeout).get_seconds()
152 )
153 except ISO8601SyntaxError:
154 try:
155 timeout = int(opts.remote_timeout)
156 except ValueError:
157 raise InputError(
158 f"Invalid timeout: {opts.remote_timeout}. Must be "
159 "an ISO 8601 duration or number of seconds."
160 ) from None
161 opts.remote_timeout = str(timeout)
162
163
164 def prompt(workflows: Iterable[str]) -> None:
165 """Ask user if they want to clean the given set of workflows."""
166 print("Would clean the following workflows:")
167 for workflow in workflows:
168 print(f' {workflow}')
169
170 if is_terminal():
171 while True:
172 ret = input('Remove these workflows (y/n): ')
173 if ret.lower() == 'y':
174 return
175 if ret.lower() == 'n':
176 sys.exit(1)
177 else:
178 print(
179 "Use --yes to remove multiple workflows in non-interactive mode.",
180 file=sys.stderr
181 )
182 sys.exit(1)
183
184
185 async def scan(
186 workflows: Iterable[str], multi_mode: bool
187 ) -> Tuple[List[str], bool]:
188 """Expand tuncated workflow IDs
189
190 For example "one" might expand to "one/run1" & "one/run2"
191 or "one/two/run1".
192
193 Returns (workflows, multi_mode)
194 """
195 ret = []
196 for workflow in list(workflows):
197 contained_flows = await get_contained_workflows(workflow)
198 if contained_flows:
199 ret.extend(contained_flows)
200 multi_mode = True
201 else:
202 ret.append(workflow)
203 return ret, multi_mode
204
205
206 async def run(*ids: str, opts: 'Values') -> None:
207 if opts.no_scan:
208 workflows: Iterable[str] = ids
209 else:
210 # parse ids from the CLI
211 workflows, multi_mode = await parse_ids_async(
212 *ids,
213 constraint='workflows',
214 match_workflows=True,
215 match_active=False,
216 infer_latest_runs=False, # don't infer latest runs like other cmds
217 )
218
219 # expand partial workflow ids (including run names)
220 workflows, multi_mode = await scan(workflows, multi_mode)
221
222 if not workflows:
223 LOG.warning(f"No stopped workflows matching {', '.join(ids)}")
224 return
225
226 workflows.sort()
227 if multi_mode and not opts.skip_interactive:
228 prompt(workflows) # prompt for approval or exit
229
230 failed = False
231 for workflow in workflows:
232 try:
233 init_clean(workflow, opts)
234 except Exception as exc:
235 failed = True
236 LOG.error(f"Failed to clean {workflow}\nError: {exc}")
237 if cylc.flow.flags.verbosity > 0:
238 LOG.exception(exc)
239 if failed:
240 raise CylcError("Clean failed")
241
242
243 @cli_function(get_option_parser)
244 def main(_parser, opts: 'Values', *ids: str):
245 _main(opts, *ids)
246
247
248 def _main(opts: 'Values', *ids: str):
249 """Run the clean command.
250
251 This is a separate function for ease of testing.
252 """
253 if cylc.flow.flags.verbosity < 2:
254 set_timestamps(LOG, False)
255
256 if opts.local_only and opts.remote_only:
257 raise InputError(
258 "--local and --remote options are mutually exclusive"
259 )
260
261 parse_timeout(opts)
262
263 asyncio.run(run(*ids, opts=opts))