Debian Codegraph @

config_tempest/services/services.py

raw
1 # Copyright 2013, 2016, 2018 Red Hat, Inc.
2 # All Rights Reserved.
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
17 import importlib
18 import pkgutil
19 import pyclbr
20
21 from six.moves import urllib
22
23 from config_tempest import constants as C
24 from config_tempest.services import horizon
25 from tempest.lib import exceptions
26
27 import config_tempest.services
28
29
30 class Services(object):
31 def __init__(self, clients, conf, creds):
32 self._clients = clients
33 self._conf = conf
34 self._creds = creds
35 self._ssl_validation = creds.disable_ssl_certificate_validation
36 self._region = clients.identity_region
37 self._services = []
38 self._service_classes = []
39 self.set_catalog_and_url()
40 self.available_services = self.get_available_services()
41
42 self.discover()
43
44 @property
45 def service_classes(self):
46 """Return the list of classes available under config_tempest.services.
47
48 This return the list of classes that inherit from base.Service
49 """
50 if not self._service_classes:
51 path = config_tempest.services.__path__
52 prefix = config_tempest.services.__name__ + '.'
53 for importer, modname, ispkg in pkgutil.walk_packages(
54 path=path, prefix=prefix, onerror=lambda x: None):
55 module_info = pyclbr.readmodule(modname)
56 for item in module_info.values():
57 m = importlib.import_module(modname)
58 c = getattr(m, item.name)
59 if issubclass(c, config_tempest.services.base.Service):
60 self._service_classes.append(c)
61
62 return self._service_classes
63
64 def get_available_services(self):
65 try:
66 services = self._clients.service_client.list_services()['services']
67 except exceptions.Forbidden:
68 C.LOG.warning("User has no permissions to list services, using "
69 "catalog. Services without endpoint will not be "
70 "discovered.")
71 services = self.catalog
72 return services
73
74 def get_service_data(self, s_name, s_type):
75 for s in self.catalog:
76 if s['name'] == s_name and s['type'] == s_type:
77 return s
78 return None
79
80 def discover(self):
81 # We loop through the classes we have for each service, and if we find
82 # a class that match a service enabled, we add it in our services list.
83 # some services doesn't have endpoints, so we need to check first
84 for s_class in self.service_classes:
85 s_types = s_class.get_service_type()
86 for s_type in s_types:
87 s_name = [t['name'] for t in self.available_services
88 if t['type'] == s_type]
89 if s_name:
90 # In the general case, there should only be one service in
91 # a deployment per service type
92 # https://docs.openstack.org/keystone/latest/contributor/
93 # service-catalog.html#services
94 if len(s_name) > 1:
95 C.LOG.warning("There are more service names ('%s') for"
96 " '%s' service type, which is undefined"
97 " behavior. Continuing with '%s'.",
98 str(s_name), s_type, s_name[0])
99 s_name = s_name[0]
100 service_data = self.get_service_data(s_name, s_type)
101 url = None
102 if not service_data:
103 C.LOG.warning('No endpoint data found for %s', s_name)
104 else:
105 url = self.parse_endpoints(self.get_endpoints(
106 service_data), s_type)
107
108 # Create the service class and add it to services list
109 service = s_class(s_name, s_type, url, self.token,
110 self._ssl_validation,
111 self._clients.get_service_client(
112 s_type),
113 ca_certs=self._creds.ca_certs)
114 # discover extensions of the service
115 service.set_extensions()
116
117 # discover versions of the service
118 service.set_versions()
119 self.merge_exts_multiversion_service(service)
120
121 # default tempest options
122 service.set_default_tempest_options(self._conf)
123
124 service.set_availability(self._conf, True)
125
126 self._services.append(service)
127 else:
128 # service is not available
129 # quickly instantiate a class in order to set
130 # availability of the service
131 s = s_class(None, None, None, None, None)
132 s.set_availability(self._conf, False)
133
134 def merge_exts_multiversion_service(self, service):
135 """Merges extensions of a service given by its name
136
137 Looking for extensions from all versions of the service
138 defined by name and merges them to that provided service.
139
140 :param service: Service object
141 """
142 versions = service.get_supported_versions()
143 service_type = service.get_unversioned_service_type()
144 services_lst = []
145 for v in versions:
146 if self.is_service(**{'type': service_type + v}):
147 services_lst.append(self.get_service(service_type + v))
148 services_lst.append(service)
149 service.extensions = self.merge_extensions(services_lst)
150
151 def get_endpoints(self, entry):
152 for ep in entry['endpoints']:
153 if self._creds.api_version == 3:
154 if (ep['region'] == self._region and
155 ep['interface'] == 'public'):
156 return ep
157 else:
158 if ep['region'] == self._region:
159 return ep
160 try:
161 return entry['endpoints'][0]
162 except IndexError:
163 return []
164
165 def set_catalog_and_url(self):
166 if self._creds.api_version == 3:
167 service_catalog = 'catalog'
168 self.public_url = 'url'
169 else:
170 service_catalog = 'serviceCatalog'
171 self.public_url = 'publicURL'
172 self.token, auth_data = self._clients.auth_provider.get_auth()
173 self.catalog = auth_data[service_catalog]
174
175 def parse_endpoints(self, ep, name):
176 """Parse an endpoint(s).
177
178 :param ep: endpoint(s)
179 :type ep: dict or list in case of no endpoints
180 :param name: name of a service
181 :type name: string
182 :return: url
183 :rtype: string
184 """
185 # endpoint list can be empty
186 if len(ep) == 0:
187 url = ""
188 C.LOG.info("Service %s has no endpoints", name)
189 else:
190 url = ep[self.public_url]
191 if 'identity' in urllib.parse.urlparse(url).path:
192 url = self.edit_identity_url(ep[self.public_url])
193 return url
194
195 def edit_identity_url(self, url):
196 """A port and identity version are added to url if contains 'identity'
197
198 :param url: url address of an endpoint
199 :type url: string
200 :rtype: string
201 """
202 # self._clients.auth_provider.auth_url stores identity.uri(_v3) value
203 # from TempestConf
204 port = urllib.parse.urlparse(self._clients.auth_provider.auth_url).port
205 if port is None:
206 port = ""
207 else:
208 port = ":" + str(port)
209 replace_text = port + "/identity/" + self._creds.identity_version
210 return url.replace("/identity", replace_text)
211
212 def get_service(self, s_type):
213 """Finds and returns a service object
214
215 :param s_type: Type of a service
216 :type s_type: string
217 :return: Service object
218 """
219 for service in self._services:
220 if service.s_type == s_type:
221 return service
222 return None
223
224 def is_service(self, **kwargs):
225 """Returns true if a service is available, false otherwise
226
227 :param kwargs: Search parameters (accepts service name or type)
228 :rtype: boolean
229 """
230 a_s = self.available_services
231 if kwargs.get('name'):
232 if [s for s in a_s if s['name'] == kwargs.get('name')]:
233 return True
234 return False
235
236 if kwargs.get('type'):
237 if [s for s in a_s if s['type'] == kwargs.get('type')]:
238 return True
239 return False
240 return False
241
242 def post_configuration(self):
243 for s in self._services:
244 s.post_configuration(self._conf, self.is_service)
245
246 horizon_kwargs = {
247 "disable_ssl_certificate_validation": self._ssl_validation
248 }
249 horizon.configure_horizon(self._conf, **horizon_kwargs)
250
251 def set_supported_api_versions(self):
252 # set supported API versions for services with more of them
253 for service in self._services:
254 versions = service.get_versions()
255 supported_versions = service.get_supported_versions()
256 if versions:
257 section = service.get_feature_name() + '-feature-enabled'
258 for s_version in supported_versions:
259 is_supported = any(s_version in item
260 for item in versions)
261 self._conf.set(
262 section, 'api_' + s_version, str(is_supported))
263
264 def merge_extensions(self, service_objects):
265 """Merges extensions from all provided service objects
266
267 :param service_objects:
268 :type service_objects: list
269 :return: Merged extensions
270 :rtype: list
271 """
272 extensions = []
273 for o in service_objects:
274 if o:
275 extensions += o.extensions
276 return extensions
277
278 def set_service_extensions(self):
279 postfix = "-feature-enabled"
280 try:
281 keystone_v3_support = self._conf.getboolean('identity' + postfix,
282 'api_v3')
283 except ValueError:
284 keystone_v3_support = False
285 if keystone_v3_support:
286 self.get_service('identity').set_identity_v3_extensions()
287
288 for service in self._services:
289 ext_key = service.get_service_extension_key()
290 if ext_key:
291 extensions = ','.join(service.get_extensions())
292 service_name = service.get_feature_name()
293 self._conf.set(service_name + postfix, ext_key, extensions)