| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
from oslo_utils import encodeutils |
| 28 |
from oslo_utils import uuidutils |
| 29 |
|
| 30 |
from glanceclient._i18n import _ |
| 31 |
from glanceclient.v1.apiclient import exceptions |
| 32 |
|
| 33 |
|
| 34 |
def find_resource(manager, name_or_id, **find_args): |
| 35 |
"""Look for resource in a given manager. |
| 36 |
|
| 37 |
Used as a helper for the _find_* methods. |
| 38 |
Example: |
| 39 |
|
| 40 |
.. code-block:: python |
| 41 |
|
| 42 |
def _find_hypervisor(cs, hypervisor): |
| 43 |
#Get a hypervisor by name or ID. |
| 44 |
return cliutils.find_resource(cs.hypervisors, hypervisor) |
| 45 |
""" |
| 46 |
|
| 47 |
try: |
| 48 |
return manager.get(int(name_or_id)) |
| 49 |
except (TypeError, ValueError, exceptions.NotFound): |
| 50 |
pass |
| 51 |
|
| 52 |
|
| 53 |
try: |
| 54 |
tmp_id = encodeutils.safe_decode(name_or_id) |
| 55 |
|
| 56 |
if uuidutils.is_uuid_like(tmp_id): |
| 57 |
return manager.get(tmp_id) |
| 58 |
except (TypeError, ValueError, exceptions.NotFound): |
| 59 |
pass |
| 60 |
|
| 61 |
|
| 62 |
if getattr(manager, 'is_alphanum_id_allowed', False): |
| 63 |
try: |
| 64 |
return manager.get(name_or_id) |
| 65 |
except exceptions.NotFound: |
| 66 |
pass |
| 67 |
|
| 68 |
try: |
| 69 |
try: |
| 70 |
return manager.find(human_id=name_or_id, **find_args) |
| 71 |
except exceptions.NotFound: |
| 72 |
pass |
| 73 |
|
| 74 |
|
| 75 |
try: |
| 76 |
resource = getattr(manager, 'resource_class', None) |
| 77 |
name_attr = resource.NAME_ATTR if resource else 'name' |
| 78 |
kwargs = {name_attr: name_or_id} |
| 79 |
kwargs.update(find_args) |
| 80 |
return manager.find(**kwargs) |
| 81 |
except exceptions.NotFound: |
| 82 |
msg = _("No %(name)s with a name or " |
| 83 |
"ID of '%(name_or_id)s' exists.") % { |
| 84 |
"name": manager.resource_class.__name__.lower(), |
| 85 |
"name_or_id": name_or_id |
| 86 |
} |
| 87 |
raise exceptions.CommandError(msg) |
| 88 |
except exceptions.NoUniqueMatch: |
| 89 |
msg = _("Multiple %(name)s matches found for " |
| 90 |
"'%(name_or_id)s', use an ID to be more specific.") % { |
| 91 |
"name": manager.resource_class.__name__.lower(), |
| 92 |
"name_or_id": name_or_id |
| 93 |
} |
| 94 |
raise exceptions.CommandError(msg) |