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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
|
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import operator
import re
from rally.common import logging
from rally.common.plugin import plugin
from rally import exceptions
from rally.task import types
from rally_openstack.common import osclients
from rally_openstack.common.services.image import image
from rally_openstack.common.services.storage import block
LOG = logging.getLogger(__name__)
configure = plugin.configure
class OpenStackResourceType(types.ResourceType):
"""A base class for OpenStack ResourceTypes plugins with help-methods"""
def __init__(self, context=None, cache=None):
super(OpenStackResourceType, self).__init__(context, cache)
self._clients = None
if self._context.get("admin"):
self._clients = osclients.Clients(
self._context["admin"]["credential"])
elif self._context.get("users"):
self._clients = osclients.Clients(
self._context["users"][0]["credential"])
def _find_resource(self, resource_spec, resources):
"""Return the resource whose name matches the pattern.
.. note:: This method is a modified version of
`rally.task.types.obj_from_name`. The difference is supporting the
case of returning the latest version of resource in case of
`accurate=False` option.
:param resource_spec: resource specification to find.
Expected keys:
* name - The exact name of resource to search. If no exact match
and value of *accurate* key is False (default behaviour), name
will be interpreted as a regexp
* regexp - a regexp of resource name to match. If several resources
match and value of *accurate* key is False (default behaviour),
the latest resource will be returned.
:param resources: iterable containing all resources
:raises InvalidScenarioArgument: if the pattern does
not match anything.
:returns: resource object mapped to `name` or `regex`
"""
if "name" in resource_spec:
# In a case of pattern string exactly matches resource name
matching_exact = [resource for resource in resources
if resource.name == resource_spec["name"]]
if len(matching_exact) == 1:
return matching_exact[0]
elif len(matching_exact) > 1:
raise exceptions.InvalidScenarioArgument(
"%(typename)s with name '%(pattern)s' "
"is ambiguous, possible matches "
"by id: %(ids)s" % {
"typename": self.get_name().title(),
"pattern": resource_spec["name"],
"ids": ", ".join(map(operator.attrgetter("id"),
matching_exact))})
if resource_spec.get("accurate", False):
raise exceptions.InvalidScenarioArgument(
"%(typename)s with name '%(name)s' not found" % {
"typename": self.get_name().title(),
"name": resource_spec["name"]})
# Else look up as regex
patternstr = resource_spec["name"]
elif "regex" in resource_spec:
patternstr = resource_spec["regex"]
else:
raise exceptions.InvalidScenarioArgument(
"%(typename)s 'id', 'name', or 'regex' not found "
"in '%(resource_spec)s' " % {
"typename": self.get_name().title(),
"resource_spec": resource_spec})
pattern = re.compile(patternstr)
matching = [resource for resource in resources
if re.search(pattern, resource.name or "")]
if not matching:
raise exceptions.InvalidScenarioArgument(
"%(typename)s with pattern '%(pattern)s' not found" % {
"typename": self.get_name().title(),
"pattern": pattern.pattern})
elif len(matching) > 1:
if not resource_spec.get("accurate", False):
return sorted(matching, key=lambda o: o.name or "")[-1]
raise exceptions.InvalidScenarioArgument(
"%(typename)s with name '%(pattern)s' is ambiguous, possible "
"matches by id: %(ids)s" % {
"typename": self.get_name().title(),
"pattern": pattern.pattern,
"ids": ", ".join(map(operator.attrgetter("id"),
matching))})
return matching[0]
@plugin.configure(name="nova_flavor")
class Flavor(OpenStackResourceType):
"""Find Nova's flavor ID by name or regexp."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
if not resource_id:
novaclient = self._clients.nova()
resource_id = types._id_from_name(
resource_config=resource_spec,
resources=novaclient.flavors.list(),
typename="flavor")
return resource_id
@plugin.configure(name="glance_image")
class GlanceImage(OpenStackResourceType):
"""Find Glance's image ID by name or regexp."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
list_kwargs = resource_spec.get("list_kwargs", {})
if not resource_id:
cache_id = hash(frozenset(list_kwargs.items()))
if cache_id not in self._cache:
glance = image.Image(self._clients)
self._cache[cache_id] = glance.list_images(**list_kwargs)
images = self._cache[cache_id]
resource = self._find_resource(resource_spec, images)
return resource.id
return resource_id
@plugin.configure(name="glance_image_args")
class GlanceImageArguments(OpenStackResourceType):
"""Process Glance image create options to look similar in case of V1/V2."""
def pre_process(self, resource_spec, config):
resource_spec = copy.deepcopy(resource_spec)
if "is_public" in resource_spec:
if "visibility" in resource_spec:
resource_spec.pop("is_public")
else:
visibility = ("public" if resource_spec.pop("is_public")
else "private")
resource_spec["visibility"] = visibility
return resource_spec
@plugin.configure(name="ec2_image")
class EC2Image(OpenStackResourceType):
"""Find EC2 image ID."""
def pre_process(self, resource_spec, config):
if "name" not in resource_spec and "regex" not in resource_spec:
# NOTE(wtakase): gets resource name from OpenStack id
glanceclient = self._clients.glance()
resource_name = types._name_from_id(
resource_config=resource_spec,
resources=list(glanceclient.images.list()),
typename="image")
resource_spec["name"] = resource_name
# NOTE(wtakase): gets EC2 resource id from name or regex
ec2client = self._clients.ec2()
resource_ec2_id = types._id_from_name(
resource_config=resource_spec,
resources=list(ec2client.get_all_images()),
typename="ec2_image")
return resource_ec2_id
@plugin.configure(name="cinder_volume_type")
class VolumeType(OpenStackResourceType):
"""Find Cinder volume type ID by name or regexp."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
if not resource_id:
cinder = block.BlockStorage(self._clients)
resource_id = types._id_from_name(
resource_config=resource_spec,
resources=cinder.list_types(),
typename="volume_type")
return resource_id
@plugin.configure(name="neutron_network")
class NeutronNetwork(OpenStackResourceType):
"""Find Neutron network ID by it's name."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
if resource_id:
return resource_id
else:
neutronclient = self._clients.neutron()
for net in neutronclient.list_networks()["networks"]:
if net["name"] == resource_spec.get("name"):
return net["id"]
raise exceptions.InvalidScenarioArgument(
"Neutron network with name '{name}' not found".format(
name=resource_spec.get("name")))
@plugin.configure(name="watcher_strategy")
class WatcherStrategy(OpenStackResourceType):
"""Find Watcher strategy ID by it's name."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
if not resource_id:
watcherclient = self._clients.watcher()
resource_id = types._id_from_name(
resource_config=resource_spec,
resources=[watcherclient.strategy.get(
resource_spec.get("name"))],
typename="strategy",
id_attr="uuid")
return resource_id
@plugin.configure(name="watcher_goal")
class WatcherGoal(OpenStackResourceType):
"""Find Watcher goal ID by it's name."""
def pre_process(self, resource_spec, config):
resource_id = resource_spec.get("id")
if not resource_id:
watcherclient = self._clients.watcher()
resource_id = types._id_from_name(
resource_config=resource_spec,
resources=[watcherclient.goal.get(resource_spec.get("name"))],
typename="goal",
id_attr="uuid")
return resource_id
|