Debian Codegraph @

cylc/flow/command_polling.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 """Encapsulates polling activity for CLI commands."""
17
18 import sys
19 from time import sleep
20 from cylc.flow import LOG
21
22
23 class Poller:
24 """Encapsulates polling activity for cylc commands. Derived classes
25 must override the check() method to test the polling condition."""
26
27 @classmethod
28 def add_to_cmd_options(cls, parser, d_interval=60, d_max_polls=10):
29 """Add command line options for commands that can do polling."""
30 parser.add_option(
31 "--max-polls",
32 help=r"Maximum number of polls (default: %default).",
33 type="int",
34 metavar="INT",
35 action="store",
36 dest="max_polls",
37 default=d_max_polls
38 )
39 parser.add_option(
40 "--interval",
41 help=r"Polling interval in seconds (default: %default).",
42 type="int",
43 metavar="SECS",
44 action="store",
45 dest="interval",
46 default=d_interval
47 )
48
49 def __init__(self, condition, interval, max_polls, args):
50 self.condition = condition # e.g. "workflow stopped"
51 self.interval = interval
52 self.max_polls = max_polls or 1 # no point in zero polls
53 self.args = args # any extra parameters needed by check()
54
55 async def check(self):
56 """Abstract method. Test polling condition."""
57 raise NotImplementedError()
58
59 async def poll(self):
60 """Poll for the condition embodied by self.check().
61
62 Return True if condition met, or False if polling exhausted.
63
64 """
65 n_polls = 0
66 result = False
67
68 while True:
69 n_polls += 1
70 result = await self.check()
71 if self.max_polls != 1:
72 sys.stderr.write(".")
73 sys.stderr.flush()
74 if result or n_polls >= self.max_polls:
75 if self.max_polls != 1:
76 sys.stderr.write("\n")
77 sys.stderr.flush()
78 break
79 sleep(self.interval)
80
81 if result:
82 return True
83 else:
84 LOG.error(f"failed after {n_polls} polls")
85 return False