| 1 |
# Copyright 2012-2013 OpenStack Foundation |
| 2 |
# |
| 3 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 4 |
# not use this file except in compliance with the License. You may obtain |
| 5 |
# a copy of the License at |
| 6 |
# |
| 7 |
# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
# |
| 9 |
# Unless required by applicable law or agreed to in writing, software |
| 10 |
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 11 |
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 12 |
# License for the specific language governing permissions and limitations |
| 13 |
# under the License. |
| 14 |
# |
| 15 |
|
| 16 |
"""Common client utilities""" |
| 17 |
|
| 18 |
import argparse |
| 19 |
import collections.abc |
| 20 |
import copy |
| 21 |
import functools |
| 22 |
import getpass |
| 23 |
import logging |
| 24 |
import os |
| 25 |
import time |
| 26 |
import typing as ty |
| 27 |
import uuid |
| 28 |
import warnings |
| 29 |
|
| 30 |
from cliff import columns as cliff_columns |
| 31 |
from openstack import resource |
| 32 |
from oslo_utils import importutils |
| 33 |
|
| 34 |
from osc_lib import exceptions |
| 35 |
from osc_lib.i18n import _ |
| 36 |
|
| 37 |
LOG = logging.getLogger(__name__) |
| 38 |
|
| 39 |
_T = ty.TypeVar('_T') |
| 40 |
|
| 41 |
|
| 42 |
def backward_compat_col_lister( |
| 43 |
column_headers: list[str], |
| 44 |
columns: list[str], |
| 45 |
column_map: dict[str, str], |
| 46 |
) -> list[str]: |
| 47 |
"""Convert the column headers to keep column backward compatibility. |
| 48 |
|
| 49 |
Replace the new column name of column headers by old name, so that |
| 50 |
the column headers can continue to support to show the old column name by |
| 51 |
--column/-c option with old name, like: volume list -c 'Display Name' |
| 52 |
|
| 53 |
:param column_headers: The column headers to be output in list command. |
| 54 |
:param columns: The columns to be output. |
| 55 |
:param column_map: The key of map is old column name, the value is new |
| 56 |
column name, like: {'old_col': 'new_col'} |
| 57 |
""" |
| 58 |
if not columns: |
| 59 |
return column_headers |
| 60 |
# NOTE(RuiChen): column_headers may be a tuple in some code, like: |
| 61 |
# volume v1, convert it to a list in order to change |
| 62 |
# the column name. |
| 63 |
column_headers = list(column_headers) |
| 64 |
for old_col, new_col in column_map.items(): |
| 65 |
if old_col in columns: |
| 66 |
LOG.warning( |
| 67 |
_( |
| 68 |
'The column "%(old_column)s" was deprecated, ' |
| 69 |
'please use "%(new_column)s" replace.' |
| 70 |
) |
| 71 |
% {'old_column': old_col, 'new_column': new_col} |
| 72 |
) |
| 73 |
if new_col in column_headers: |
| 74 |
column_headers[column_headers.index(new_col)] = old_col |
| 75 |
return column_headers |
| 76 |
|
| 77 |
|
| 78 |
def backward_compat_col_showone( |
| 79 |
show_object: collections.abc.MutableMapping[str, _T], |
| 80 |
columns: list[str], |
| 81 |
column_map: dict[str, str], |
| 82 |
) -> collections.abc.MutableMapping[str, _T]: |
| 83 |
"""Convert the output object to keep column backward compatibility. |
| 84 |
|
| 85 |
Replace the new column name of output object by old name, so that |
| 86 |
the object can continue to support to show the old column name by |
| 87 |
--column/-c option with old name, like: volume show -c 'display_name' |
| 88 |
|
| 89 |
:param show_object: The object to be output in create/show commands. |
| 90 |
:param columns: The columns to be output. |
| 91 |
:param column_map: The key of map is old column name, the value is new |
| 92 |
column name, like: {'old_col': 'new_col'} |
| 93 |
""" |
| 94 |
if not columns: |
| 95 |
return show_object |
| 96 |
|
| 97 |
show_object = copy.deepcopy(show_object) |
| 98 |
for old_col, new_col in column_map.items(): |
| 99 |
if old_col in columns: |
| 100 |
LOG.warning( |
| 101 |
_( |
| 102 |
'The column "%(old_column)s" was deprecated, ' |
| 103 |
'please use "%(new_column)s" replace.' |
| 104 |
) |
| 105 |
% {'old_column': old_col, 'new_column': new_col} |
| 106 |
) |
| 107 |
if new_col in show_object: |
| 108 |
show_object.update({old_col: show_object.pop(new_col)}) |
| 109 |
return show_object |
| 110 |
|
| 111 |
|
| 112 |
def build_kwargs_dict(arg_name: str, value: _T) -> dict[str, _T]: |
| 113 |
"""Return a dictionary containing `arg_name` if `value` is set.""" |
| 114 |
kwargs = {} |
| 115 |
if value: |
| 116 |
kwargs[arg_name] = value |
| 117 |
return kwargs |
| 118 |
|
| 119 |
|
| 120 |
def calculate_header_and_attrs( |
| 121 |
column_headers: collections.abc.Sequence[str], |
| 122 |
attrs: collections.abc.Sequence[str], |
| 123 |
parsed_args: argparse.Namespace, |
| 124 |
) -> tuple[collections.abc.Sequence[str], collections.abc.Sequence[str]]: |
| 125 |
"""Calculate headers and attribute names based on parsed_args.column. |
| 126 |
|
| 127 |
When --column (-c) option is specified, this function calculates |
| 128 |
column headers and expected API attribute names according to |
| 129 |
the OSC header/column definitions. |
| 130 |
|
| 131 |
This function also adjusts the content of parsed_args.columns |
| 132 |
if API attribute names are used in parsed_args.columns. |
| 133 |
This allows users to specify API attribute names in -c option. |
| 134 |
|
| 135 |
:param column_headers: A tuple/list of column headers to display |
| 136 |
:param attrs: a tuple/list of API attribute names. The order of |
| 137 |
corresponding column header and API attribute name must match. |
| 138 |
:param parsed_args: Parsed argument object returned by argparse parse_args |
| 139 |
:returns: A tuple of calculated headers and API attribute names. |
| 140 |
""" |
| 141 |
if parsed_args.columns: |
| 142 |
header_attr_map = dict(zip(column_headers, attrs)) |
| 143 |
expected_attrs = [ |
| 144 |
header_attr_map.get(c, c) for c in parsed_args.columns |
| 145 |
] |
| 146 |
attr_header_map = dict(zip(attrs, column_headers)) |
| 147 |
expected_headers = [ |
| 148 |
attr_header_map.get(c, c) for c in parsed_args.columns |
| 149 |
] |
| 150 |
# If attribute name is used in parsed_args.columns |
| 151 |
# convert it into display names because cliff expects |
| 152 |
# name in parsed_args.columns and name in column_headers matches. |
| 153 |
parsed_args.columns = expected_headers |
| 154 |
return expected_headers, expected_attrs |
| 155 |
else: |
| 156 |
return column_headers, attrs |
| 157 |
|
| 158 |
|
| 159 |
def env(*vars: str, **kwargs: ty.Any) -> str | None: |
| 160 |
"""Search for the first defined of possibly many env vars |
| 161 |
|
| 162 |
Returns the first environment variable defined in vars, or |
| 163 |
returns the default defined in kwargs. |
| 164 |
""" |
| 165 |
for v in vars: |
| 166 |
value = os.environ.get(v, None) |
| 167 |
if value: |
| 168 |
return value |
| 169 |
|
| 170 |
if 'default' in kwargs and kwargs['default'] is not None: |
| 171 |
return str(kwargs['default']) |
| 172 |
|
| 173 |
return None |
| 174 |
|
| 175 |
|
| 176 |
def find_min_match( |
| 177 |
items: collections.abc.Sequence[_T], |
| 178 |
sort_attr: str, |
| 179 |
**kwargs: ty.Any, |
| 180 |
) -> collections.abc.Sequence[_T]: |
| 181 |
"""Find all resources meeting the given minimum constraints |
| 182 |
|
| 183 |
:param items: A List of objects to consider |
| 184 |
:param sort_attr: Attribute to sort the resulting list |
| 185 |
:param kwargs: A dict of attributes and their minimum values |
| 186 |
:rtype: A list of resources osrted by sort_attr that meet the minimums |
| 187 |
""" |
| 188 |
|
| 189 |
def minimum_pieces_of_flair(item: _T) -> bool: |
| 190 |
"""Find lowest value greater than the minumum""" |
| 191 |
|
| 192 |
result = True |
| 193 |
for k in kwargs: |
| 194 |
# AND together all of the given attribute results |
| 195 |
result = result and kwargs[k] <= get_field(item, k) |
| 196 |
return result |
| 197 |
|
| 198 |
return sort_items(list(filter(minimum_pieces_of_flair, items)), sort_attr) |
| 199 |
|
| 200 |
|
| 201 |
# TODO(stephenfin): We should return a proper type, but how to do so without |
| 202 |
# using generics? We should also deprecate this but there are a lot of users |
| 203 |
# still. |
| 204 |
def find_resource( |
| 205 |
manager: ty.Any, |
| 206 |
name_or_id: str, |
| 207 |
**kwargs: ty.Any, |
| 208 |
) -> ty.Any: |
| 209 |
"""Helper for the _find_* methods. |
| 210 |
|
| 211 |
:param manager: A client manager class |
| 212 |
:param name_or_id: The resource we are trying to find |
| 213 |
:param kwargs: To be used in calling .find() |
| 214 |
:rtype: The found resource |
| 215 |
|
| 216 |
This method will attempt to find a resource in a variety of ways. |
| 217 |
Primarily .get() methods will be called with `name_or_id` as an integer |
| 218 |
value, and tried again as a string value. |
| 219 |
|
| 220 |
If both fail, then a .find() is attempted, which is essentially calling |
| 221 |
a .list() function with a 'name' query parameter that is set to |
| 222 |
`name_or_id`. |
| 223 |
|
| 224 |
Lastly, if any kwargs are passed in, they will be treated as additional |
| 225 |
query parameters. This is particularly handy in the case of finding |
| 226 |
resources in a domain. |
| 227 |
|
| 228 |
""" |
| 229 |
|
| 230 |
# Case 1: name_or_id is an ID, we need to call get() directly |
| 231 |
# for example: /projects/454ad1c743e24edcad846d1118837cac |
| 232 |
# For some projects, the name only will work. For keystone, this is not |
| 233 |
# enough information, and domain information is necessary. |
| 234 |
try: |
| 235 |
return manager.get(name_or_id) |
| 236 |
except Exception: # noqa: S110 |
| 237 |
pass |
| 238 |
|
| 239 |
if kwargs: |
| 240 |
# Case 2: name_or_id is a name, but we have query args in kwargs |
| 241 |
# for example: /projects/demo&domain_id=30524568d64447fbb3fa8b7891c10dd |
| 242 |
try: |
| 243 |
return manager.get(name_or_id, **kwargs) |
| 244 |
except Exception: # noqa: S110 |
| 245 |
pass |
| 246 |
|
| 247 |
# Case 3: Try to get entity as integer id. Keystone does not have integer |
| 248 |
# IDs, they are UUIDs, but some things in nova do, like flavors. |
| 249 |
try: |
| 250 |
if isinstance(name_or_id, int) or name_or_id.isdigit(): |
| 251 |
return manager.get(int(name_or_id), **kwargs) |
| 252 |
# FIXME(dtroyer): The exception to catch here is dependent on which |
| 253 |
# client library the manager passed in belongs to. |
| 254 |
# Eventually this should be pulled from a common set |
| 255 |
# of client exceptions. |
| 256 |
except Exception as ex: |
| 257 |
if ( |
| 258 |
type(ex).__name__ == 'NotFound' |
| 259 |
or type(ex).__name__ == 'HTTPNotFound' |
| 260 |
or type(ex).__name__ == 'TypeError' |
| 261 |
): |
| 262 |
pass |
| 263 |
else: |
| 264 |
raise |
| 265 |
|
| 266 |
# Case 4: Try to use find. |
| 267 |
# Reset the kwargs here for find |
| 268 |
if len(kwargs) == 0: |
| 269 |
kwargs = {} |
| 270 |
|
| 271 |
try: |
| 272 |
# Prepare the kwargs for calling find |
| 273 |
if 'NAME_ATTR' in manager.resource_class.__dict__: |
| 274 |
# novaclient does this for oddball resources |
| 275 |
kwargs[manager.resource_class.NAME_ATTR] = name_or_id |
| 276 |
else: |
| 277 |
kwargs['name'] = name_or_id |
| 278 |
except Exception: # noqa: S110 |
| 279 |
pass |
| 280 |
|
| 281 |
# finally try to find entity by name |
| 282 |
try: |
| 283 |
return manager.find(**kwargs) |
| 284 |
# FIXME(dtroyer): The exception to catch here is dependent on which |
| 285 |
# client library the manager passed in belongs to. |
| 286 |
# Eventually this should be pulled from a common set |
| 287 |
# of client exceptions. |
| 288 |
except Exception as ex: |
| 289 |
if type(ex).__name__ == 'NotFound': |
| 290 |
msg = _("No %(resource)s with a name or ID of '%(id)s' exists.") |
| 291 |
raise exceptions.CommandError( |
| 292 |
msg |
| 293 |
% { |
| 294 |
'resource': manager.resource_class.__name__.lower(), |
| 295 |
'id': name_or_id, |
| 296 |
} |
| 297 |
) |
| 298 |
if type(ex).__name__ == 'NoUniqueMatch': |
| 299 |
msg = _( |
| 300 |
"More than one %(resource)s exists with the name '%(id)s'." |
| 301 |
) |
| 302 |
raise exceptions.CommandError( |
| 303 |
msg |
| 304 |
% { |
| 305 |
'resource': manager.resource_class.__name__.lower(), |
| 306 |
'id': name_or_id, |
| 307 |
} |
| 308 |
) |
| 309 |
else: |
| 310 |
pass |
| 311 |
|
| 312 |
# Case 5: For client with no find function, list all resources and hope |
| 313 |
# to find a matching name or ID. |
| 314 |
count = 0 |
| 315 |
for res in manager.list(): |
| 316 |
if res.get('id') == name_or_id or res.get('name') == name_or_id: |
| 317 |
count += 1 |
| 318 |
_res = res |
| 319 |
if count == 0: |
| 320 |
# we found no match, report back this error: |
| 321 |
msg = _("Could not find resource %s") |
| 322 |
raise exceptions.CommandError(msg % name_or_id) |
| 323 |
elif count == 1: |
| 324 |
return _res |
| 325 |
else: |
| 326 |
# we found multiple matches, report back this error |
| 327 |
msg = _("More than one resource exists with the name or ID '%s'.") |
| 328 |
raise exceptions.CommandError(msg % name_or_id) |
| 329 |
|
| 330 |
|
| 331 |
def format_dict(data: dict[str, ty.Any], prefix: str | None = None) -> str: |
| 332 |
"""Return a formatted string of key value pairs |
| 333 |
|
| 334 |
:param data: a dict |
| 335 |
:param prefix: the current parent keys in a recursive call |
| 336 |
:rtype: a string formatted to key='value' |
| 337 |
""" |
| 338 |
|
| 339 |
if data is None: |
| 340 |
return None |
| 341 |
|
| 342 |
output = "" |
| 343 |
for s in sorted(data): |
| 344 |
if prefix: |
| 345 |
key_str = ".".join([prefix, s]) |
| 346 |
else: |
| 347 |
key_str = s |
| 348 |
if isinstance(data[s], dict): |
| 349 |
# NOTE(dtroyer): Only append the separator chars here, quoting |
| 350 |
# is completely handled in the terminal case. |
| 351 |
output = output + format_dict(data[s], prefix=key_str) + ", " |
| 352 |
elif data[s] is not None: |
| 353 |
output = output + key_str + "='" + str(data[s]) + "', " |
| 354 |
else: |
| 355 |
output = output + key_str + "=, " |
| 356 |
return output[:-2] |
| 357 |
|
| 358 |
|
| 359 |
def format_dict_of_list( |
| 360 |
data: dict[str, list[ty.Any]] | None, separator: str = '; ' |
| 361 |
) -> str | None: |
| 362 |
"""Return a formatted string of key value pair |
| 363 |
|
| 364 |
:param data: a dict, key is string, value is a list of string, for example: |
| 365 |
{'public': ['2001:db8::8', '172.24.4.6']} |
| 366 |
:param separator: the separator to use between key/value pair |
| 367 |
(default: '; ') |
| 368 |
:return: a string formatted to {'key1'=['value1', 'value2']} with separated |
| 369 |
by separator |
| 370 |
""" |
| 371 |
if data is None: |
| 372 |
return None |
| 373 |
|
| 374 |
output = [] |
| 375 |
for key in sorted(data): |
| 376 |
value = data[key] |
| 377 |
if value is None: |
| 378 |
continue |
| 379 |
value_str = format_list(value) |
| 380 |
group = f"{key}={value_str}" |
| 381 |
output.append(group) |
| 382 |
|
| 383 |
return separator.join(output) |
| 384 |
|
| 385 |
|
| 386 |
def format_list( |
| 387 |
data: list[ty.Any] | None, separator: str = ', ' |
| 388 |
) -> str | None: |
| 389 |
"""Return a formatted strings |
| 390 |
|
| 391 |
:param data: a list of strings |
| 392 |
:param separator: the separator to use between strings (default: ', ') |
| 393 |
:rtype: a string formatted based on separator |
| 394 |
""" |
| 395 |
if data is None: |
| 396 |
return None |
| 397 |
|
| 398 |
return separator.join(sorted(data)) |
| 399 |
|
| 400 |
|
| 401 |
def format_list_of_dicts( |
| 402 |
data: list[dict[str, ty.Any]] | None, |
| 403 |
) -> str | None: |
| 404 |
"""Return a formatted string of key value pairs for each dict |
| 405 |
|
| 406 |
:param data: a list of dicts |
| 407 |
:rtype: a string formatted to key='value' with dicts separated by new line |
| 408 |
""" |
| 409 |
if data is None: |
| 410 |
return None |
| 411 |
|
| 412 |
return '\n'.join(format_dict(i) for i in data) |
| 413 |
|
| 414 |
|
| 415 |
def format_size(size: int | float | None) -> str: |
| 416 |
"""Display size of a resource in a human readable format |
| 417 |
|
| 418 |
:param size: |
| 419 |
The size of the resource in bytes. |
| 420 |
|
| 421 |
:returns: |
| 422 |
Returns the size in human-friendly format |
| 423 |
:rtype string: |
| 424 |
|
| 425 |
This function converts the size (provided in bytes) of a resource |
| 426 |
into a human-friendly format such as K, M, G, T, P, E, Z |
| 427 |
""" |
| 428 |
|
| 429 |
suffix = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z'] |
| 430 |
base = 1000.0 |
| 431 |
index = 0 |
| 432 |
|
| 433 |
size_ = float(size) if size is not None else 0.0 |
| 434 |
while size_ >= base: |
| 435 |
index = index + 1 |
| 436 |
size_ = size_ / base |
| 437 |
|
| 438 |
padded = f'{size_:.1f}' |
| 439 |
stripped = padded.rstrip('0').rstrip('.') |
| 440 |
|
| 441 |
return f'{stripped}{suffix[index]}' |
| 442 |
|
| 443 |
|
| 444 |
def get_client_class( |
| 445 |
api_name: str, |
| 446 |
version: str | int | float, |
| 447 |
version_map: dict[str, str], |
| 448 |
) -> ty.Any: |
| 449 |
"""Returns the client class for the requested API version |
| 450 |
|
| 451 |
:param api_name: the name of the API, e.g. 'compute', 'image', etc |
| 452 |
:param version: the requested API version |
| 453 |
:param version_map: a dict of client class strings keyed by version |
| 454 |
:rtype: a client class for the requested API version |
| 455 |
""" |
| 456 |
warnings.warn( |
| 457 |
"This function is deprecated and is not necessary with openstacksdk." |
| 458 |
"Consider vendoring this if necessary.", |
| 459 |
category=DeprecationWarning, |
| 460 |
) |
| 461 |
|
| 462 |
try: |
| 463 |
client_path = version_map[str(version)] |
| 464 |
except (KeyError, ValueError): |
| 465 |
sorted_versions = sorted( |
| 466 |
version_map.keys(), key=lambda s: list(map(int, s.split('.'))) |
| 467 |
) |
| 468 |
msg = _( |
| 469 |
"Invalid %(api_name)s client version '%(version)s'. " |
| 470 |
"must be one of: %(version_map)s" |
| 471 |
) |
| 472 |
raise exceptions.UnsupportedVersion( |
| 473 |
msg |
| 474 |
% { |
| 475 |
'api_name': api_name, |
| 476 |
'version': version, |
| 477 |
'version_map': ', '.join(sorted_versions), |
| 478 |
} |
| 479 |
) |
| 480 |
|
| 481 |
return importutils.import_class(client_path) |
| 482 |
|
| 483 |
|
| 484 |
FormatterT = ( |
| 485 |
type[cliff_columns.FormattableColumn[ty.Any]] | functools.partial[ty.Any] |
| 486 |
) |
| 487 |
|
| 488 |
|
| 489 |
def get_dict_properties( |
| 490 |
item: dict[str, _T], |
| 491 |
fields: collections.abc.Sequence[str], |
| 492 |
mixed_case_fields: collections.abc.Sequence[str] | None = None, |
| 493 |
formatters: collections.abc.Mapping[str, FormatterT] | None = None, |
| 494 |
) -> tuple[ty.Any, ...]: |
| 495 |
"""Return a tuple containing the item properties. |
| 496 |
|
| 497 |
:param item: a single dict resource |
| 498 |
:param fields: tuple of strings with the desired field names |
| 499 |
:param mixed_case_fields: tuple of field names to preserve case |
| 500 |
:param formatters: dictionary mapping field names to callables |
| 501 |
to format the values |
| 502 |
""" |
| 503 |
if mixed_case_fields is None: |
| 504 |
mixed_case_fields = [] |
| 505 |
if formatters is None: |
| 506 |
formatters = {} |
| 507 |
|
| 508 |
row = [] |
| 509 |
|
| 510 |
for field in fields: |
| 511 |
if field in mixed_case_fields: |
| 512 |
field_name = field.replace(' ', '_') |
| 513 |
else: |
| 514 |
field_name = field.lower().replace(' ', '_') |
| 515 |
data: ty.Any = item[field_name] if field_name in item else '' |
| 516 |
if field in formatters: |
| 517 |
formatter = formatters[field] |
| 518 |
# columns must be either a subclass of FormattableColumn |
| 519 |
if isinstance(formatter, type) and issubclass( |
| 520 |
formatter, cliff_columns.FormattableColumn |
| 521 |
): |
| 522 |
data = formatter(data) |
| 523 |
# or a partial wrapping one (to allow us to pass extra parameters) |
| 524 |
elif ( |
| 525 |
isinstance(formatter, functools.partial) |
| 526 |
and isinstance(formatter.func, type) |
| 527 |
and issubclass(formatter.func, cliff_columns.FormattableColumn) |
| 528 |
): |
| 529 |
data = formatter(data) |
| 530 |
# otherwise it's invalid |
| 531 |
else: |
| 532 |
msg = "Invalid formatter provided." |
| 533 |
raise exceptions.CommandError(msg) |
| 534 |
|
| 535 |
row.append(data) |
| 536 |
|
| 537 |
return tuple(row) |
| 538 |
|
| 539 |
|
| 540 |
def get_item_properties( |
| 541 |
item: dict[str, _T], |
| 542 |
fields: collections.abc.Sequence[str], |
| 543 |
mixed_case_fields: collections.abc.Sequence[str] | None = None, |
| 544 |
formatters: collections.abc.Mapping[str, FormatterT] | None = None, |
| 545 |
) -> tuple[ty.Any, ...]: |
| 546 |
"""Return a tuple containing the item properties. |
| 547 |
|
| 548 |
:param item: a single item resource (e.g. Server, Project, etc) |
| 549 |
:param fields: tuple of strings with the desired field names |
| 550 |
:param mixed_case_fields: tuple of field names to preserve case |
| 551 |
:param formatters: dictionary mapping field names to callables |
| 552 |
to format the values |
| 553 |
""" |
| 554 |
if mixed_case_fields is None: |
| 555 |
mixed_case_fields = [] |
| 556 |
if formatters is None: |
| 557 |
formatters = {} |
| 558 |
|
| 559 |
row = [] |
| 560 |
|
| 561 |
for field in fields: |
| 562 |
if field in mixed_case_fields: |
| 563 |
field_name = field.replace(' ', '_') |
| 564 |
else: |
| 565 |
field_name = field.lower().replace(' ', '_') |
| 566 |
data = getattr(item, field_name, '') |
| 567 |
if field in formatters: |
| 568 |
formatter = formatters[field] |
| 569 |
# columns must be either a subclass of FormattableColumn |
| 570 |
if isinstance(formatter, type) and issubclass( |
| 571 |
formatter, cliff_columns.FormattableColumn |
| 572 |
): |
| 573 |
data = formatter(data) |
| 574 |
# or a partial wrapping one (to allow us to pass extra parameters) |
| 575 |
elif ( |
| 576 |
isinstance(formatter, functools.partial) |
| 577 |
and isinstance(formatter.func, type) |
| 578 |
and issubclass(formatter.func, cliff_columns.FormattableColumn) |
| 579 |
): |
| 580 |
data = formatter(data) |
| 581 |
# otherwise it's invalid |
| 582 |
else: |
| 583 |
msg = "Invalid formatter provided." |
| 584 |
raise exceptions.CommandError(msg) |
| 585 |
|
| 586 |
row.append(data) |
| 587 |
return tuple(row) |
| 588 |
|
| 589 |
|
| 590 |
def get_effective_log_level() -> int: |
| 591 |
"""Returns the lowest logging level considered by logging handlers |
| 592 |
|
| 593 |
Retrieve and return the smallest log level set among the root |
| 594 |
logger's handlers (in case of multiple handlers). |
| 595 |
""" |
| 596 |
root_log = logging.getLogger() |
| 597 |
min_log_lvl = logging.CRITICAL |
| 598 |
for handler in root_log.handlers: |
| 599 |
min_log_lvl = min(min_log_lvl, handler.level) |
| 600 |
return min_log_lvl |
| 601 |
|
| 602 |
|
| 603 |
def get_field(item: _T, field: str) -> ty.Any: |
| 604 |
try: |
| 605 |
if isinstance(item, dict): |
| 606 |
return item[field] |
| 607 |
else: |
| 608 |
return getattr(item, field) |
| 609 |
except Exception: |
| 610 |
msg = _("Resource doesn't have field %s") |
| 611 |
raise exceptions.CommandError(msg % field) |
| 612 |
|
| 613 |
|
| 614 |
def get_password( |
| 615 |
stdin: ty.TextIO, |
| 616 |
prompt: str | None = None, |
| 617 |
confirm: bool = True, |
| 618 |
) -> str: |
| 619 |
message = prompt or "User Password:" |
| 620 |
if hasattr(stdin, 'isatty') and stdin.isatty(): |
| 621 |
try: |
| 622 |
while True: |
| 623 |
first_pass = getpass.getpass(message) |
| 624 |
if not confirm: |
| 625 |
return first_pass |
| 626 |
second_pass = getpass.getpass("Repeat " + message) |
| 627 |
if first_pass == second_pass: |
| 628 |
return first_pass |
| 629 |
msg = _("The passwords entered were not the same") |
| 630 |
print(msg) |
| 631 |
except EOFError: # Ctl-D |
| 632 |
msg = _("Error reading password") |
| 633 |
raise exceptions.CommandError(msg) |
| 634 |
msg = _("No terminal detected attempting to read password") |
| 635 |
raise exceptions.CommandError(msg) |
| 636 |
|
| 637 |
|
| 638 |
def is_ascii(string: str | bytes) -> bool: |
| 639 |
try: |
| 640 |
if isinstance(string, bytes): |
| 641 |
string.decode('ascii') |
| 642 |
else: |
| 643 |
string.encode('ascii') |
| 644 |
return True |
| 645 |
except (UnicodeEncodeError, UnicodeDecodeError): |
| 646 |
return False |
| 647 |
|
| 648 |
|
| 649 |
def read_blob_file_contents(blob_file: str) -> str: |
| 650 |
try: |
| 651 |
with open(blob_file) as file: |
| 652 |
blob = file.read().strip() |
| 653 |
return blob |
| 654 |
except OSError: |
| 655 |
msg = _("Error occurred trying to read from file %s") |
| 656 |
raise exceptions.CommandError(msg % blob_file) |
| 657 |
|
| 658 |
|
| 659 |
def sort_items( |
| 660 |
items: collections.abc.Sequence[_T], |
| 661 |
sort_str: str, |
| 662 |
sort_type: type[ty.Any] | None = None, |
| 663 |
) -> collections.abc.Sequence[_T]: |
| 664 |
"""Sort items based on sort keys and sort directions given by sort_str. |
| 665 |
|
| 666 |
:param items: a list or generator object of items |
| 667 |
:param sort_str: a string defining the sort rules, the format is |
| 668 |
'<key1>:[direction1],<key2>:[direction2]...', direction can be 'asc' |
| 669 |
for ascending or 'desc' for descending, if direction is not given, |
| 670 |
it's ascending by default |
| 671 |
:return: sorted items |
| 672 |
""" |
| 673 |
if not sort_str: |
| 674 |
return items |
| 675 |
# items may be a generator object, transform it to a list |
| 676 |
items = list(items) |
| 677 |
sort_keys = sort_str.strip().split(',') |
| 678 |
for sort_key in reversed(sort_keys): |
| 679 |
reverse = False |
| 680 |
if ':' in sort_key: |
| 681 |
sort_key, direction = sort_key.split(':', 1) |
| 682 |
if not sort_key: |
| 683 |
msg = _("'<empty string>'' is not a valid sort key") |
| 684 |
raise exceptions.CommandError(msg) |
| 685 |
if direction not in ['asc', 'desc']: |
| 686 |
if not direction: |
| 687 |
direction = "<empty string>" |
| 688 |
msg = _( |
| 689 |
"'%(direction)s' is not a valid sort direction for " |
| 690 |
"sort key %(sort_key)s, use 'asc' or 'desc' instead" |
| 691 |
) |
| 692 |
raise exceptions.CommandError( |
| 693 |
msg |
| 694 |
% { |
| 695 |
'direction': direction, |
| 696 |
'sort_key': sort_key, |
| 697 |
} |
| 698 |
) |
| 699 |
if direction == 'desc': |
| 700 |
reverse = True |
| 701 |
|
| 702 |
def f(x: ty.Any) -> ty.Any: |
| 703 |
# Attempts to convert items to same 'sort_type' if provided. |
| 704 |
# This is due to Python 3 throwing TypeError if you attempt to |
| 705 |
# compare different types |
| 706 |
item = get_field(x, sort_key) |
| 707 |
if sort_type and not isinstance(item, sort_type): |
| 708 |
try: |
| 709 |
item = sort_type(item) |
| 710 |
except Exception: |
| 711 |
# Can't convert, so no sensible way to compare |
| 712 |
item = sort_type() |
| 713 |
return item |
| 714 |
|
| 715 |
items.sort(key=f, reverse=reverse) |
| 716 |
|
| 717 |
return items |
| 718 |
|
| 719 |
|
| 720 |
def wait_for_delete( |
| 721 |
manager: ty.Any, |
| 722 |
res_id: str, |
| 723 |
status_field: str = 'status', |
| 724 |
error_status: collections.abc.Sequence[str] = ['error'], |
| 725 |
exception_name: collections.abc.Sequence[str] = ['NotFound'], |
| 726 |
sleep_time: int = 5, |
| 727 |
timeout: int = 300, |
| 728 |
callback: collections.abc.Callable[[int], None] | None = None, |
| 729 |
) -> bool: |
| 730 |
"""Wait for resource deletion |
| 731 |
|
| 732 |
:param manager: the manager from which we can get the resource |
| 733 |
:param res_id: the resource id to watch |
| 734 |
:param status_field: the status attribute in the returned resource object, |
| 735 |
this is used to check for error states while the resource is being |
| 736 |
deleted |
| 737 |
:param error_status: a list of status strings for error |
| 738 |
:param exception_name: a list of exception strings for deleted case |
| 739 |
:param sleep_time: wait this long between checks (seconds) |
| 740 |
:param timeout: check until this long (seconds) |
| 741 |
:param callback: called per sleep cycle, useful to display progress; this |
| 742 |
function is passed a progress value during each iteration of the wait |
| 743 |
loop |
| 744 |
:rtype: True on success, False if the resource has gone to error state or |
| 745 |
the timeout has been reached |
| 746 |
""" |
| 747 |
warnings.warn( |
| 748 |
"This function is deprecated as it does not support openstacksdk " |
| 749 |
"clients. Consider vendoring this if necessary.", |
| 750 |
category=DeprecationWarning, |
| 751 |
) |
| 752 |
|
| 753 |
total_time = 0 |
| 754 |
while total_time < timeout: |
| 755 |
try: |
| 756 |
# might not be a bad idea to re-use find_resource here if it was |
| 757 |
# a bit more friendly in the exceptions it raised so we could just |
| 758 |
# handle a NotFound exception here without parsing the message |
| 759 |
res = manager.get(res_id) |
| 760 |
except Exception as ex: |
| 761 |
if type(ex).__name__ in exception_name: |
| 762 |
return True |
| 763 |
raise |
| 764 |
|
| 765 |
status = getattr(res, status_field, '').lower() |
| 766 |
if status in error_status: |
| 767 |
return False |
| 768 |
|
| 769 |
if callback: |
| 770 |
progress = getattr(res, 'progress', None) or 0 |
| 771 |
callback(progress) |
| 772 |
time.sleep(sleep_time) |
| 773 |
total_time += sleep_time |
| 774 |
|
| 775 |
# if we got this far we've timed out |
| 776 |
return False |
| 777 |
|
| 778 |
|
| 779 |
def wait_for_status( |
| 780 |
status_f: collections.abc.Callable[[str], object], |
| 781 |
res_id: str, |
| 782 |
status_field: str = 'status', |
| 783 |
success_status: collections.abc.Sequence[str] = ['active'], |
| 784 |
error_status: collections.abc.Sequence[str] = ['error'], |
| 785 |
sleep_time: int = 5, |
| 786 |
callback: collections.abc.Callable[[int], None] | None = None, |
| 787 |
) -> bool: |
| 788 |
"""Wait for status change on a resource during a long-running operation |
| 789 |
|
| 790 |
:param status_f: a status function that takes a single id argument |
| 791 |
:param res_id: the resource id to watch |
| 792 |
:param status_field: the status attribute in the returned resource object |
| 793 |
:param success_status: a list of status strings for successful completion |
| 794 |
:param error_status: a list of status strings for error |
| 795 |
:param sleep_time: wait this long (seconds) |
| 796 |
:param callback: called per sleep cycle, useful to display progress |
| 797 |
:rtype: True on success |
| 798 |
""" |
| 799 |
warnings.warn( |
| 800 |
"This function is deprecated as it does not support openstacksdk " |
| 801 |
"clients. Consider vendoring this if necessary.", |
| 802 |
category=DeprecationWarning, |
| 803 |
) |
| 804 |
|
| 805 |
while True: |
| 806 |
res = status_f(res_id) |
| 807 |
status = getattr(res, status_field, '').lower() |
| 808 |
if status in success_status: |
| 809 |
retval = True |
| 810 |
break |
| 811 |
elif status in error_status: |
| 812 |
retval = False |
| 813 |
break |
| 814 |
if callback: |
| 815 |
progress = getattr(res, 'progress', None) or 0 |
| 816 |
callback(progress) |
| 817 |
time.sleep(sleep_time) |
| 818 |
return retval |
| 819 |
|
| 820 |
|
| 821 |
def get_osc_show_columns_for_sdk_resource( |
| 822 |
sdk_resource: resource.Resource, |
| 823 |
osc_column_map: dict[str, str], |
| 824 |
invisible_columns: collections.abc.Sequence[str] | None = None, |
| 825 |
) -> tuple[tuple[str, ...], tuple[str, ...]]: |
| 826 |
"""Get and filter the display and attribute columns for an SDK resource. |
| 827 |
|
| 828 |
Common utility function for preparing the output of an OSC show command. |
| 829 |
Some of the columns may need to get renamed, others made invisible. |
| 830 |
|
| 831 |
:param sdk_resource: An SDK resource |
| 832 |
:param osc_column_map: A hash of mappings for display column names |
| 833 |
:param invisible_columns: A list of invisible column names |
| 834 |
|
| 835 |
:returns: Two tuples containing the names of the display and attribute |
| 836 |
columns |
| 837 |
""" |
| 838 |
|
| 839 |
if getattr(sdk_resource, 'allow_fetch', None) is not None: |
| 840 |
# OSC at the moment lands here with FakeResource objects which are not |
| 841 |
# 100% sdk compatible. Unless we introduce SDK test/fake resources we |
| 842 |
# should check presence of the specific method |
| 843 |
resource_dict = sdk_resource.to_dict( |
| 844 |
body=True, headers=False, ignore_none=False |
| 845 |
) |
| 846 |
else: |
| 847 |
# We might land here with not a real SDK Resource (during the |
| 848 |
# transition period). |
| 849 |
resource_dict = sdk_resource |
| 850 |
|
| 851 |
# Build the OSC column names to display for the SDK resource. |
| 852 |
attr_map = {} |
| 853 |
display_columns = list(resource_dict.keys()) |
| 854 |
invisible_columns = [] if invisible_columns is None else invisible_columns |
| 855 |
for col_name in invisible_columns: |
| 856 |
if col_name in display_columns: |
| 857 |
display_columns.remove(col_name) |
| 858 |
for sdk_attr, osc_attr in osc_column_map.items(): |
| 859 |
if sdk_attr in display_columns: |
| 860 |
attr_map[osc_attr] = sdk_attr |
| 861 |
display_columns.remove(sdk_attr) |
| 862 |
if osc_attr not in display_columns: |
| 863 |
display_columns.append(osc_attr) |
| 864 |
sorted_display_columns = sorted(display_columns) |
| 865 |
|
| 866 |
# Build the SDK attribute names for the OSC column names. |
| 867 |
attr_columns = [] |
| 868 |
for column in sorted_display_columns: |
| 869 |
new_column = attr_map[column] if column in attr_map else column |
| 870 |
attr_columns.append(new_column) |
| 871 |
return tuple(sorted_display_columns), tuple(attr_columns) |
| 872 |
|
| 873 |
|
| 874 |
def is_uuid_like(value: ty.Any) -> bool: |
| 875 |
"""Returns validation of a value as a UUID. |
| 876 |
|
| 877 |
:param val: Value to verify |
| 878 |
:returns: True if UUID-like, else False. |
| 879 |
""" |
| 880 |
if not isinstance(value, str): |
| 881 |
return False |
| 882 |
|
| 883 |
try: |
| 884 |
formatted_value = ( |
| 885 |
value.replace('urn:', '') |
| 886 |
.replace('uuid:', '') |
| 887 |
.strip('{}') |
| 888 |
.replace('-', '') |
| 889 |
.lower() |
| 890 |
) |
| 891 |
return str(uuid.UUID(value)).replace('-', '') == formatted_value |
| 892 |
except (TypeError, ValueError, AttributeError): |
| 893 |
return False |