Debian Codegraph @

config_tempest/services/base.py

raw
1 # Copyright 2013 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 import json
17 import re
18 import urllib3
19
20 from six.moves import urllib
21
22 from config_tempest.constants import LOG
23
24 from tempest.lib import exceptions
25
26
27 MULTIPLE_SLASH = re.compile(r'/+')
28
29
30 class ServiceError(Exception):
31 pass
32
33
34 class Service(object):
35 def __init__(self, name, s_type, service_url, token,
36 disable_ssl_validation, client=None, **kwargs):
37 self.name = name
38 self.s_type = s_type
39 self.service_url = service_url
40 self.headers = {'Accept': 'application/json', 'X-Auth-Token': token}
41 self.disable_ssl_validation = disable_ssl_validation
42 self.ca_certs = kwargs.get('ca_certs', None)
43 self.client = client
44
45 self.extensions = []
46 self.versions = []
47 self.versions_body = {'versions': []}
48
49 def do_get(self, url, top_level=False, top_level_path=""):
50 parts = list(urllib.parse.urlparse(url))
51 # 2 is the path offset
52 if top_level:
53 parts[2] = '/' + top_level_path
54
55 parts[2] = MULTIPLE_SLASH.sub('/', parts[2])
56 url = urllib.parse.urlunparse(parts)
57
58 try:
59 if self.disable_ssl_validation:
60 urllib3.disable_warnings()
61 http = urllib3.PoolManager(cert_reqs='CERT_NONE')
62 elif self.ca_certs is not None:
63 http = urllib3.PoolManager(
64 cert_reqs='REQUIRED', ca_certs=self.ca_certs
65 )
66 else:
67 http = urllib3.PoolManager()
68 r = http.request('GET', url, headers=self.headers)
69 except Exception as e:
70 LOG.error("Request on service '%s' with url '%s' failed",
71 self.s_type, url)
72 raise e
73
74 if r.status == 403:
75 raise exceptions.Forbidden("Request on service '%s' with url '%s' "
76 "failed with code 403" % (self.s_type,
77 url))
78
79 if r.status >= 400:
80 raise ServiceError("Request on service '%s' with url '%s' failed"
81 " with code %d" % (self.s_type, url, r.status))
82 return r.data.decode('utf-8')
83
84 def set_extensions(self):
85 self.extensions = []
86
87 def set_versions(self):
88 self.versions = []
89
90 def set_availability(self, conf, available):
91 """Sets service's availability.
92
93 The services's codename will be set to desired value under
94 [service_available] section in tempest.conf during the services
95 discovery process.
96 """
97 try:
98 conf.set('service_available', self.get_codename(), str(available))
99 except NotImplementedError:
100 pass
101
102 def get_extensions(self):
103 return self.extensions
104
105 @staticmethod
106 def get_service_type():
107 """Return the service type.
108
109 This returns a list because you can have services with more types,
110 like volume, volumev2, volumev3.
111 """
112 return []
113
114 def get_versions(self):
115 """Return the versions available for each service.
116
117 This doesn't mean tempestconf supports all these versions. Only that
118 the service has these api versions enabled.
119 """
120 return self.versions
121
122 def set_default_tempest_options(self, conf):
123 pass
124
125 def get_supported_versions(self):
126 """Return the versions supported by tempestconf.
127
128 The server might have older or newer versions that could not be
129 supported by tempestconf.
130 """
131 return []
132
133 @staticmethod
134 def get_codename():
135 """Return the service_available name of the service.
136
137 This name is used when setting service availability in
138 set_availability method. If the method is not implemented, service
139 availability is not set.
140 """
141 raise NotImplementedError
142
143 def get_feature_name(self):
144 """Return the name of service used in <service>-feature-enabled.
145
146 Some services have the -feature-enabled option in tempest, that
147 diverges from the service name. The main example is object-store
148 service where the <service>-feature-enabled is object-storage.
149 """
150 return self.s_type
151
152 def get_service_extension_key(self):
153 """Return the extension key for a particular service"""
154 return None
155
156 def get_unversioned_service_type(self):
157 """Return type of service without versions.
158
159 Some services are versioned like volumev2 and volumev3, we try to
160 discover these services checking the supported versions, so we need
161 to know the unversioned service type for this.
162 The default value is the type of the service.
163 """
164 return self.s_type
165
166 def post_configuration(self, conf, is_service):
167 """Do post congiruation steps.
168
169 :param conf: config_tempest.tempest_conf.TempestConf
170 :param is_service: config_tempest.services.services.Services.is_service
171 """
172 return None
173
174
175 class VersionedService(Service):
176 def set_versions(self, top_level=True):
177 body = self.do_get(self.service_url, top_level=top_level)
178 self.versions_body = json.loads(body)
179 self.versions = self.deserialize_versions(self.versions_body)
180
181 def deserialize_versions(self, body):
182 versions = []
183 for version in body['versions']:
184 if version['status'] != "DEPRECATED":
185 versions.append(version)
186 return list(map(lambda x: x['id'], versions))
187
188 def filter_api_microversions(self, max_version='version'):
189 min_microversion = ''
190 max_microversion = ''
191 for version in self.versions_body['versions']:
192 if version['status'] != "DEPRECATED":
193 if max_microversion == '':
194 max_microversion = version[max_version]
195 else:
196 max_microversion = max(max_microversion,
197 version[max_version])
198 if 'min_version' not in version:
199 continue
200 if min_microversion == '':
201 min_microversion = version['min_version']
202 else:
203 min_microversion = min(min_microversion,
204 version['min_version'])
205 return {'max_microversion': max_microversion,
206 'min_microversion': min_microversion}
207
208 def no_port_cut_url(self):
209 # if there is no port defined, cut the url from version to the end
210 u = urllib3.util.parse_url(self.service_url)
211 url = self.service_url
212 if u.port is None:
213 found = re.findall(r'v\d', url)
214 if len(found) > 0:
215 index = url.index(found[0])
216 url = self.service_url[:index]
217 return (url, u.port is not None)