blob: a07612adacbae386e26704563d4a7ed924a01715 [file] [log] [blame]
Kurt Taylor6a6f5be2013-04-02 18:53:47 -04001# Copyright 2013 IBM Corp.
Matthew Treinish72ea4422013-02-07 14:42:49 -05002# 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
16import copy
Attila Fazekas5c068812013-02-14 15:29:44 +010017import errno
Matthew Treinish72ea4422013-02-07 14:42:49 -050018import os
Attila Fazekase72b7cd2013-03-26 18:34:21 +010019import time
Matthew Treinish72ea4422013-02-07 14:42:49 -050020
Doug Hellmann583ce2c2015-03-11 14:55:46 +000021from oslo_log import log as logging
Matthew Treinish21905512015-07-13 10:33:35 -040022from oslo_serialization import jsonutils as json
Matthew Treinish71426682015-04-23 11:19:38 -040023import six
Matthew Treinish89128142015-04-23 10:44:30 -040024from six.moves.urllib import parse as urllib
Matthew Treinish01472ff2015-02-20 17:26:52 -050025from tempest_lib.common.utils import misc as misc_utils
Masayuki Igawabfa07602015-01-20 18:47:17 +090026from tempest_lib import exceptions as lib_exc
27
Matthew Treinish72ea4422013-02-07 14:42:49 -050028from tempest.common import glance_http
Ken'ichi Ohmichi0e836652015-01-08 04:38:56 +000029from tempest.common import service_client
Matthew Treinish72ea4422013-02-07 14:42:49 -050030from tempest import exceptions
Matthew Treinish72ea4422013-02-07 14:42:49 -050031
Attila Fazekase72b7cd2013-03-26 18:34:21 +010032LOG = logging.getLogger(__name__)
33
Matthew Treinish72ea4422013-02-07 14:42:49 -050034
Ken'ichi Ohmichia6287072015-07-02 02:43:15 +000035class ImageClient(service_client.ServiceClient):
Matthew Treinish72ea4422013-02-07 14:42:49 -050036
Masayuki Igawabc7e1892015-03-03 11:46:48 +090037 def __init__(self, auth_provider, catalog_type, region, endpoint_type=None,
38 build_interval=None, build_timeout=None,
39 disable_ssl_certificate_validation=None,
David Kranz85b660b2015-03-23 10:26:52 -040040 ca_certs=None, trace_requests=None):
Ken'ichi Ohmichia6287072015-07-02 02:43:15 +000041 super(ImageClient, self).__init__(
Ken'ichi Ohmichi0690ea42015-01-02 07:03:51 +000042 auth_provider,
Masayuki Igawabc7e1892015-03-03 11:46:48 +090043 catalog_type,
44 region,
45 endpoint_type=endpoint_type,
46 build_interval=build_interval,
47 build_timeout=build_timeout,
48 disable_ssl_certificate_validation=(
49 disable_ssl_certificate_validation),
50 ca_certs=ca_certs,
David Kranz85b660b2015-03-23 10:26:52 -040051 trace_requests=trace_requests)
Andrea Frittoli8bbdb162014-01-06 11:06:13 +000052 self._http = None
Masayuki Igawabc7e1892015-03-03 11:46:48 +090053 self.dscv = disable_ssl_certificate_validation
54 self.ca_certs = ca_certs
Matthew Treinish72ea4422013-02-07 14:42:49 -050055
56 def _image_meta_from_headers(self, headers):
57 meta = {'properties': {}}
Matthew Treinish71426682015-04-23 11:19:38 -040058 for key, value in six.iteritems(headers):
Matthew Treinish72ea4422013-02-07 14:42:49 -050059 if key.startswith('x-image-meta-property-'):
60 _key = key[22:]
61 meta['properties'][_key] = value
62 elif key.startswith('x-image-meta-'):
63 _key = key[13:]
64 meta[_key] = value
65
66 for key in ['is_public', 'protected', 'deleted']:
67 if key in meta:
68 meta[key] = meta[key].strip().lower() in ('t', 'true', 'yes',
69 '1')
70 for key in ['size', 'min_ram', 'min_disk']:
71 if key in meta:
72 try:
73 meta[key] = int(meta[key])
74 except ValueError:
75 pass
76 return meta
77
78 def _image_meta_to_headers(self, fields):
79 headers = {}
80 fields_copy = copy.deepcopy(fields)
Attila Fazekase72b7cd2013-03-26 18:34:21 +010081 copy_from = fields_copy.pop('copy_from', None)
82 if copy_from is not None:
83 headers['x-glance-api-copy-from'] = copy_from
Matthew Treinish71426682015-04-23 11:19:38 -040084 for key, value in six.iteritems(fields_copy.pop('properties', {})):
Matthew Treinish72ea4422013-02-07 14:42:49 -050085 headers['x-image-meta-property-%s' % key] = str(value)
Matthew Treinish71426682015-04-23 11:19:38 -040086 for key, value in six.iteritems(fields_copy.pop('api', {})):
Attila Fazekase72b7cd2013-03-26 18:34:21 +010087 headers['x-glance-api-property-%s' % key] = str(value)
Matthew Treinish71426682015-04-23 11:19:38 -040088 for key, value in six.iteritems(fields_copy):
Matthew Treinish72ea4422013-02-07 14:42:49 -050089 headers['x-image-meta-%s' % key] = str(value)
90 return headers
91
92 def _get_file_size(self, obj):
93 """Analyze file-like object and attempt to determine its size.
94
95 :param obj: file-like object, typically redirected from stdin.
96 :retval The file's size or None if it cannot be determined.
97 """
98 # For large images, we need to supply the size of the
99 # image file. See LP Bugs #827660 and #845788.
100 if hasattr(obj, 'seek') and hasattr(obj, 'tell'):
101 try:
102 obj.seek(0, os.SEEK_END)
103 obj_size = obj.tell()
104 obj.seek(0)
105 return obj_size
Dirk Mueller1db5db22013-06-23 20:21:32 +0200106 except IOError as e:
Matthew Treinish72ea4422013-02-07 14:42:49 -0500107 if e.errno == errno.ESPIPE:
108 # Illegal seek. This means the user is trying
109 # to pipe image data to the client, e.g.
110 # echo testdata | bin/glance add blah..., or
111 # that stdin is empty, or that a file-like
112 # object which doesn't support 'seek/tell' has
113 # been supplied.
114 return None
115 else:
116 raise
117 else:
118 # Cannot determine size of input image
119 return None
120
121 def _get_http(self):
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000122 return glance_http.HTTPClient(auth_provider=self.auth_provider,
123 filters=self.filters,
Masayuki Igawabc7e1892015-03-03 11:46:48 +0900124 insecure=self.dscv,
125 ca_certs=self.ca_certs)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500126
127 def _create_with_data(self, headers, data):
128 resp, body_iter = self.http.raw_request('POST', '/v1/images',
129 headers=headers, body=data)
130 self._error_checker('POST', '/v1/images', headers, data, resp,
131 body_iter)
132 body = json.loads(''.join([c for c in body_iter]))
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000133 return service_client.ResponseBody(resp, body['image'])
Matthew Treinish72ea4422013-02-07 14:42:49 -0500134
135 def _update_with_data(self, image_id, headers, data):
136 url = '/v1/images/%s' % image_id
137 resp, body_iter = self.http.raw_request('PUT', url, headers=headers,
138 body=data)
139 self._error_checker('PUT', url, headers, data,
140 resp, body_iter)
141 body = json.loads(''.join([c for c in body_iter]))
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000142 return service_client.ResponseBody(resp, body['image'])
Matthew Treinish72ea4422013-02-07 14:42:49 -0500143
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000144 @property
145 def http(self):
146 if self._http is None:
Masayuki Igawabc7e1892015-03-03 11:46:48 +0900147 self._http = self._get_http()
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000148 return self._http
149
Matthew Treinishce3ef922013-03-11 14:02:46 -0400150 def create_image(self, name, container_format, disk_format, **kwargs):
Matthew Treinish72ea4422013-02-07 14:42:49 -0500151 params = {
152 "name": name,
153 "container_format": container_format,
154 "disk_format": disk_format,
Matthew Treinish72ea4422013-02-07 14:42:49 -0500155 }
Matthew Treinishce3ef922013-03-11 14:02:46 -0400156
Matthew Treinish72ea4422013-02-07 14:42:49 -0500157 headers = {}
158
hi2suresh75a20302013-04-09 09:17:06 +0000159 for option in ['is_public', 'location', 'properties',
160 'copy_from', 'min_ram']:
Matthew Treinishce3ef922013-03-11 14:02:46 -0400161 if option in kwargs:
162 params[option] = kwargs.get(option)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500163
164 headers.update(self._image_meta_to_headers(params))
165
Matthew Treinishce3ef922013-03-11 14:02:46 -0400166 if 'data' in kwargs:
167 return self._create_with_data(headers, kwargs.get('data'))
Matthew Treinish72ea4422013-02-07 14:42:49 -0500168
Matthew Treinishce3ef922013-03-11 14:02:46 -0400169 resp, body = self.post('v1/images', None, headers)
David Kranz9c3b3b62014-06-19 16:05:53 -0400170 self.expected_success(201, resp.status)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500171 body = json.loads(body)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000172 return service_client.ResponseBody(resp, body['image'])
Matthew Treinish72ea4422013-02-07 14:42:49 -0500173
174 def update_image(self, image_id, name=None, container_format=None,
ivan-zhud1bbe5d2013-12-29 18:32:46 +0800175 data=None, properties=None):
Matthew Treinish72ea4422013-02-07 14:42:49 -0500176 params = {}
177 headers = {}
178 if name is not None:
179 params['name'] = name
180
181 if container_format is not None:
182 params['container_format'] = container_format
183
ivan-zhud1bbe5d2013-12-29 18:32:46 +0800184 if properties is not None:
185 params['properties'] = properties
186
Matthew Treinish72ea4422013-02-07 14:42:49 -0500187 headers.update(self._image_meta_to_headers(params))
188
189 if data is not None:
190 return self._update_with_data(image_id, headers, data)
191
192 url = 'v1/images/%s' % image_id
193 resp, body = self.put(url, data, headers)
David Kranz9c3b3b62014-06-19 16:05:53 -0400194 self.expected_success(200, resp.status)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500195 body = json.loads(body)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000196 return service_client.ResponseBody(resp, body['image'])
Matthew Treinish72ea4422013-02-07 14:42:49 -0500197
198 def delete_image(self, image_id):
199 url = 'v1/images/%s' % image_id
David Kranz9c3b3b62014-06-19 16:05:53 -0400200 resp, body = self.delete(url)
201 self.expected_success(200, resp.status)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000202 return service_client.ResponseBody(resp, body)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500203
Ken'ichi Ohmichibcad2a22015-05-22 09:37:06 +0000204 def list_images(self, detail=False, properties=dict(),
205 changes_since=None, **kwargs):
Matthew Treinish72ea4422013-02-07 14:42:49 -0500206 url = 'v1/images'
207
Ken'ichi Ohmichibcad2a22015-05-22 09:37:06 +0000208 if detail:
209 url += '/detail'
Attila Fazekas11795b52013-02-24 15:49:08 +0100210
ivan-zhuccc89462013-10-31 16:53:12 +0800211 params = {}
212 for key, value in properties.items():
213 params['property-%s' % key] = value
214
215 kwargs.update(params)
216
ivan-zhud1bbe5d2013-12-29 18:32:46 +0800217 if changes_since is not None:
218 kwargs['changes-since'] = changes_since
219
Attila Fazekas11795b52013-02-24 15:49:08 +0100220 if len(kwargs) > 0:
221 url += '?%s' % urllib.urlencode(kwargs)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500222
223 resp, body = self.get(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400224 self.expected_success(200, resp.status)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500225 body = json.loads(body)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000226 return service_client.ResponseBodyList(resp, body['images'])
Matthew Treinish72ea4422013-02-07 14:42:49 -0500227
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100228 def get_image_meta(self, image_id):
229 url = 'v1/images/%s' % image_id
230 resp, __ = self.head(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400231 self.expected_success(200, resp.status)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100232 body = self._image_meta_from_headers(resp)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000233 return service_client.ResponseBody(resp, body)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100234
Ken'ichi Ohmichi5d410762015-05-22 01:10:03 +0000235 def show_image(self, image_id):
Matthew Treinish72ea4422013-02-07 14:42:49 -0500236 url = 'v1/images/%s' % image_id
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100237 resp, body = self.get(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400238 self.expected_success(200, resp.status)
David Kranzd7e97b42015-02-16 09:37:31 -0500239 return service_client.ResponseBodyData(resp, body)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500240
241 def is_resource_deleted(self, id):
242 try:
Attila Fazekas9fa29472014-08-18 09:48:00 +0200243 self.get_image_meta(id)
Masayuki Igawabfa07602015-01-20 18:47:17 +0900244 except lib_exc.NotFound:
Matthew Treinish72ea4422013-02-07 14:42:49 -0500245 return True
246 return False
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500247
Matt Riedemannd2b96512014-10-13 10:18:16 -0700248 @property
249 def resource_type(self):
250 """Returns the primary type of resource this client works with."""
251 return 'image_meta'
252
Ken'ichi Ohmichif0df53c2015-05-22 01:16:50 +0000253 def list_image_members(self, image_id):
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500254 url = 'v1/images/%s/members' % image_id
255 resp, body = self.get(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400256 self.expected_success(200, resp.status)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500257 body = json.loads(body)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000258 return service_client.ResponseBody(resp, body)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500259
Ken'ichi Ohmichibcad2a22015-05-22 09:37:06 +0000260 def list_shared_images(self, tenant_id):
261 """List shared images with the specified tenant"""
262 url = 'v1/shared-images/%s' % tenant_id
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500263 resp, body = self.get(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400264 self.expected_success(200, resp.status)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500265 body = json.loads(body)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000266 return service_client.ResponseBody(resp, body)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500267
268 def add_member(self, member_id, image_id, can_share=False):
269 url = 'v1/images/%s/members/%s' % (image_id, member_id)
270 body = None
271 if can_share:
272 body = json.dumps({'member': {'can_share': True}})
Valeriy Ponomaryov88686d82014-02-16 12:24:51 +0200273 resp, __ = self.put(url, body)
David Kranz9c3b3b62014-06-19 16:05:53 -0400274 self.expected_success(204, resp.status)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000275 return service_client.ResponseBody(resp)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500276
277 def delete_member(self, member_id, image_id):
278 url = 'v1/images/%s/members/%s' % (image_id, member_id)
279 resp, __ = self.delete(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400280 self.expected_success(204, resp.status)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000281 return service_client.ResponseBody(resp)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500282
Attila Fazekasa8b5fe72013-08-01 16:59:06 +0200283 # NOTE(afazekas): just for the wait function
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100284 def _get_image_status(self, image_id):
David Kranz34f18782015-01-06 13:43:55 -0500285 meta = self.get_image_meta(image_id)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100286 status = meta['status']
287 return status
288
Attila Fazekasa8b5fe72013-08-01 16:59:06 +0200289 # NOTE(afazkas): Wait reinvented again. It is not in the correct layer
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100290 def wait_for_image_status(self, image_id, status):
291 """Waits for a Image to reach a given status."""
292 start_time = time.time()
293 old_value = value = self._get_image_status(image_id)
294 while True:
295 dtime = time.time() - start_time
296 time.sleep(self.build_interval)
297 if value != old_value:
298 LOG.info('Value transition from "%s" to "%s"'
299 'in %d second(s).', old_value,
300 value, dtime)
Attila Fazekas195f1d42013-10-24 10:33:16 +0200301 if value == status:
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100302 return value
303
Attila Fazekas195f1d42013-10-24 10:33:16 +0200304 if value == 'killed':
305 raise exceptions.ImageKilledException(image_id=image_id,
Attila Fazekas9dfb9072013-11-13 16:45:36 +0100306 status=status)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100307 if dtime > self.build_timeout:
308 message = ('Time Limit Exceeded! (%ds)'
309 'while waiting for %s, '
310 'but we got %s.' %
311 (self.build_timeout, status, value))
Matt Riedemann7cec3462014-06-25 12:48:43 -0700312 caller = misc_utils.find_test_caller()
313 if caller:
314 message = '(%s) %s' % (caller, message)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100315 raise exceptions.TimeoutException(message)
316 time.sleep(self.build_interval)
317 old_value = value
318 value = self._get_image_status(image_id)