Debian Codegraph @

oslo_upgradecheck/upgradecheck.py

raw symbols SCIP
1 # Copyright 2018 Red Hat Inc.
2 # Copyright 2016 IBM Corp.
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License"); you may
5 # not use this file except in compliance with the License. You may obtain
6 # a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 # License for the specific language governing permissions and limitations
14 # under the License.
15
16 from collections.abc import Callable, Iterable
17 import json
18 import sys
19 import textwrap
20 import traceback
21 from typing import Any, TypedDict
22
23 import enum
24 from oslo_config import cfg # type: ignore
25 import prettytable
26
27 from oslo_upgradecheck._i18n import _
28
29 CONF: cfg.ConfigOpts | None = None
30
31
32 class Code(enum.IntEnum):
33 """Status codes for the upgrade check command"""
34
35 # All upgrade readiness checks passed successfully and there is
36 # nothing to do.
37 SUCCESS = 0
38
39 # At least one check encountered an issue and requires further
40 # investigation. This is considered a warning but the upgrade may be OK.
41 WARNING = 1
42
43 # There was an upgrade status check failure that needs to be
44 # investigated. This should be considered something that stops an upgrade.
45 FAILURE = 2
46
47
48 UPGRADE_CHECK_MSG_MAP = {
49 Code.SUCCESS: _('Success'),
50 Code.WARNING: _('Warning'),
51 Code.FAILURE: _('Failure'),
52 }
53
54
55 class Result:
56 """Class used for 'nova-status upgrade check' results.
57
58 The 'code' attribute is a Code enum.
59 The 'details' attribute is a translated message generally only used for
60 checks that result in a warning or failure code. The details should provide
61 information on what issue was discovered along with any remediation.
62 """
63
64 def __init__(self, code: Code, details: str | None = None) -> None:
65 super().__init__()
66 self.code = code
67 self.details = details
68
69
70 class _OutputCheck(TypedDict):
71 check: str
72 result: Code
73 details: str | None
74
75
76 class _Output(TypedDict):
77 name: str
78 checks: list[_OutputCheck]
79
80
81 class UpgradeCommands:
82 """Base class for upgrade checks
83
84 This class should be inherited by a class in each project that provides
85 the actual checks. Those checks should be added to the _upgrade_checks
86 class member so that they are run when the ``check`` method is called.
87
88 The subcommands here must not rely on the service object model since they
89 should be able to run on n-1 data. Any queries to the database should be
90 done through the sqlalchemy query language directly like the database
91 schema migrations.
92 """
93
94 display_title = _('Upgrade Check Results')
95 _upgrade_checks: tuple[
96 tuple[
97 str,
98 Callable[..., Result]
99 | tuple[Callable[..., Result], dict[str, Any]],
100 ],
101 ...,
102 ] = ()
103
104 def _get_details(self, upgrade_check_result: Result) -> str | None:
105 if upgrade_check_result.details is None:
106 return None
107
108 # wrap the text on the details to 60 characters
109 return '\n'.join(
110 textwrap.wrap(
111 upgrade_check_result.details, 60, subsequent_indent=' '
112 )
113 )
114
115 def check(self) -> Code:
116 """Performs checks to see if the deployment is ready for upgrade.
117
118 These checks are expected to be run BEFORE services are restarted with
119 new code.
120
121 :returns: Code
122 """
123 return_code = Code.SUCCESS
124 # This is a list if 2-item tuples for the check name and it's results.
125 check_results = []
126 for name, func in self._upgrade_checks:
127 if isinstance(func, tuple):
128 func_name, kwargs = func
129 result = func_name(self, **kwargs)
130 else:
131 result = func(self)
132 # store the result of the check for the summary table
133 check_results.append((name, result))
134 # we want to end up with the highest level code of all checks
135 if result.code > return_code:
136 return_code = result.code
137
138 # We're going to build a summary table that looks like:
139 # +----------------------------------------------------+
140 # | Upgrade Check Results |
141 # +----------------------------------------------------+
142 # | Check: Cells v2 |
143 # | Result: Success |
144 # | Details: None |
145 # +----------------------------------------------------+
146 # | Check: Placement API |
147 # | Result: Failure |
148 # | Details: There is no placement-api endpoint in the |
149 # | service catalog. |
150 # +----------------------------------------------------+
151
152 # Since registering opts can be overridden by consuming code, we can't
153 # assume that our locally defined option exists.
154 if (
155 CONF is not None
156 and hasattr(CONF, 'command')
157 and hasattr(CONF.command, 'json')
158 and CONF.command.json
159 ):
160 # NOTE(bnemec): We use str on the translated string to
161 # force immediate translation if lazy translation is in use.
162 # See lp1801761 for details.
163 output: _Output = {'name': str(self.display_title), 'checks': []}
164 for name, result in check_results:
165 output['checks'].append(
166 {
167 'check': name,
168 'result': result.code,
169 'details': result.details,
170 }
171 )
172 print(json.dumps(output))
173 else:
174 # NOTE(bnemec): We use str on the translated string to
175 # force immediate translation if lazy translation is in use.
176 # See lp1801761 for details.
177 t = prettytable.PrettyTable(
178 [str(self.display_title)], hrules=prettytable.ALL
179 )
180 t.align = 'l'
181 for name, result in check_results:
182 cell = _(
183 'Check: %(name)s\nResult: %(result)s\nDetails: %(details)s'
184 ) % {
185 'name': name,
186 'result': UPGRADE_CHECK_MSG_MAP[result.code],
187 'details': self._get_details(result),
188 }
189 t.add_row([cell])
190 print(t)
191
192 return return_code
193
194
195 def register_cli_options(
196 conf: cfg.ConfigOpts, upgrade_command: UpgradeCommands
197 ) -> None:
198 """Set up the command line options.
199
200 Adds a subcommand to support 'upgrade check' on the command line.
201
202 :param conf: An oslo.confg ConfigOpts instance on which to register the
203 upgrade check arguments.
204 :param upgrade_command: The UpgradeCommands instance.
205 """
206
207 def add_parsers(subparsers: Any) -> None:
208 upgrade_action = subparsers.add_parser('upgrade')
209 upgrade_action.add_argument('check')
210 upgrade_action.set_defaults(action_fn=upgrade_command.check)
211 upgrade_action.add_argument(
212 '--json',
213 action='store_true',
214 help='Output the results in JSON format. Default is to print '
215 'results in human readable table format.',
216 )
217
218 opt = cfg.SubCommandOpt('command', handler=add_parsers)
219 conf.register_cli_opt(opt)
220
221
222 def run(conf: cfg.ConfigOpts) -> int:
223 """Run the requested command.
224
225 :param conf: An oslo.confg ConfigOpts instance on which the upgrade
226 commands have been previously registered.
227 """
228 try:
229 return conf.command.action_fn() # type: ignore
230 except Exception:
231 print(_('Error:\n%s') % traceback.format_exc())
232 # This is 255 so it's not confused with the upgrade check exit codes.
233 return 255
234
235
236 def main(
237 conf: cfg.ConfigOpts,
238 project: str,
239 upgrade_command: UpgradeCommands,
240 argv: list[str] = sys.argv[1:],
241 default_config_files: Iterable[str] | None = None,
242 ) -> int:
243 """Simple implementation of main for upgrade checks
244
245 This can be used in upgrade check commands to provide the minimum
246 necessary parameter handling and logic.
247
248 :param conf: An oslo.confg ConfigOpts instance on which to register the
249 upgrade check arguments.
250 :param project: The name of the project, to be used as an argument
251 to the oslo_config.ConfigOpts instance to find
252 configuration files.
253 :param upgrade_command: The UpgradeCommands instance.
254 :param argv: The command line arguments to parse. Defaults to sys.argv[1:].
255 :param default_config_files: The configuration files to load. For projects
256 that use non-standard default locations for
257 the configuration files, use this to override
258 the search behavior in oslo.config.
259
260 """
261 global CONF
262 register_cli_options(conf, upgrade_command)
263
264 conf(args=argv, project=project, default_config_files=default_config_files)
265 CONF = conf
266 return run(conf)