blob: b581203fdd3acb80c9153ce77fa8ffbca23c06cf [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
Masayuki Igawabfa07602015-01-20 18:47:17 +090025
Matthew Treinish72ea4422013-02-07 14:42:49 -050026from tempest.common import glance_http
Ken'ichi Ohmichi0e836652015-01-08 04:38:56 +000027from tempest.common import service_client
Matthew Treinish72ea4422013-02-07 14:42:49 -050028from tempest import exceptions
Andrea Frittoli (andreaf)db9672e2016-02-23 14:07:24 -050029from tempest.lib.common.utils import misc as misc_utils
30from tempest.lib import exceptions as lib_exc
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 Ohmichi69dcf442015-11-30 11:48:01 +000035class ImagesClient(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 Ohmichi69dcf442015-11-30 11:48:01 +000041 super(ImagesClient, 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]))
John Warren66207252015-07-31 15:51:02 -0400133 return service_client.ResponseBody(resp, body)
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]))
John Warren66207252015-07-31 15:51:02 -0400142 return service_client.ResponseBody(resp, body)
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
Ghanshyam86a31e12015-12-16 15:42:47 +0900150 def create_image(self, **kwargs):
Matthew Treinish72ea4422013-02-07 14:42:49 -0500151 headers = {}
Ghanshyam86a31e12015-12-16 15:42:47 +0900152 data = kwargs.pop('data', None)
153 headers.update(self._image_meta_to_headers(kwargs))
Matthew Treinish72ea4422013-02-07 14:42:49 -0500154
Ghanshyam86a31e12015-12-16 15:42:47 +0900155 if data is not None:
156 return self._create_with_data(headers, data)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500157
Matthew Treinishce3ef922013-03-11 14:02:46 -0400158 resp, body = self.post('v1/images', None, headers)
David Kranz9c3b3b62014-06-19 16:05:53 -0400159 self.expected_success(201, resp.status)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500160 body = json.loads(body)
John Warren66207252015-07-31 15:51:02 -0400161 return service_client.ResponseBody(resp, body)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500162
Ghanshyam86a31e12015-12-16 15:42:47 +0900163 def update_image(self, image_id, **kwargs):
Matthew Treinish72ea4422013-02-07 14:42:49 -0500164 headers = {}
Ghanshyam86a31e12015-12-16 15:42:47 +0900165 data = kwargs.pop('data', None)
166 headers.update(self._image_meta_to_headers(kwargs))
Matthew Treinish72ea4422013-02-07 14:42:49 -0500167
168 if data is not None:
169 return self._update_with_data(image_id, headers, data)
170
171 url = 'v1/images/%s' % image_id
Ghanshyam86a31e12015-12-16 15:42:47 +0900172 resp, body = self.put(url, None, headers)
David Kranz9c3b3b62014-06-19 16:05:53 -0400173 self.expected_success(200, resp.status)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500174 body = json.loads(body)
John Warren66207252015-07-31 15:51:02 -0400175 return service_client.ResponseBody(resp, body)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500176
177 def delete_image(self, image_id):
178 url = 'v1/images/%s' % image_id
David Kranz9c3b3b62014-06-19 16:05:53 -0400179 resp, body = self.delete(url)
180 self.expected_success(200, resp.status)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000181 return service_client.ResponseBody(resp, body)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500182
Ghanshyame60db482016-01-13 09:50:12 +0900183 def list_images(self, detail=False, **kwargs):
184 """Return a list of all images filtered by input parameters.
185
186 Available params: see http://developer.openstack.org/
187 api-ref-image-v1.html#listImage-v1
188
189 Most parameters except the following are passed to the API without
190 any changes.
191 :param changes_since: The name is changed to changes-since
192 """
Matthew Treinish72ea4422013-02-07 14:42:49 -0500193 url = 'v1/images'
194
Ken'ichi Ohmichibcad2a22015-05-22 09:37:06 +0000195 if detail:
196 url += '/detail'
Attila Fazekas11795b52013-02-24 15:49:08 +0100197
Ghanshyame60db482016-01-13 09:50:12 +0900198 properties = kwargs.pop('properties', {})
199 for key, value in six.iteritems(properties):
200 kwargs['property-%s' % key] = value
ivan-zhuccc89462013-10-31 16:53:12 +0800201
Ghanshyame60db482016-01-13 09:50:12 +0900202 if kwargs.get('changes_since'):
203 kwargs['changes-since'] = kwargs.pop('changes_since')
ivan-zhud1bbe5d2013-12-29 18:32:46 +0800204
Attila Fazekas11795b52013-02-24 15:49:08 +0100205 if len(kwargs) > 0:
206 url += '?%s' % urllib.urlencode(kwargs)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500207
208 resp, body = self.get(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400209 self.expected_success(200, resp.status)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500210 body = json.loads(body)
John Warren66207252015-07-31 15:51:02 -0400211 return service_client.ResponseBody(resp, body)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500212
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100213 def get_image_meta(self, image_id):
214 url = 'v1/images/%s' % image_id
215 resp, __ = self.head(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400216 self.expected_success(200, resp.status)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100217 body = self._image_meta_from_headers(resp)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000218 return service_client.ResponseBody(resp, body)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100219
Ken'ichi Ohmichi5d410762015-05-22 01:10:03 +0000220 def show_image(self, image_id):
Matthew Treinish72ea4422013-02-07 14:42:49 -0500221 url = 'v1/images/%s' % image_id
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100222 resp, body = self.get(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400223 self.expected_success(200, resp.status)
David Kranzd7e97b42015-02-16 09:37:31 -0500224 return service_client.ResponseBodyData(resp, body)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500225
226 def is_resource_deleted(self, id):
227 try:
Attila Fazekas9fa29472014-08-18 09:48:00 +0200228 self.get_image_meta(id)
Masayuki Igawabfa07602015-01-20 18:47:17 +0900229 except lib_exc.NotFound:
Matthew Treinish72ea4422013-02-07 14:42:49 -0500230 return True
231 return False
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500232
Matt Riedemannd2b96512014-10-13 10:18:16 -0700233 @property
234 def resource_type(self):
235 """Returns the primary type of resource this client works with."""
236 return 'image_meta'
237
Ken'ichi Ohmichif0df53c2015-05-22 01:16:50 +0000238 def list_image_members(self, image_id):
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500239 url = 'v1/images/%s/members' % image_id
240 resp, body = self.get(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400241 self.expected_success(200, resp.status)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500242 body = json.loads(body)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000243 return service_client.ResponseBody(resp, body)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500244
Ken'ichi Ohmichibcad2a22015-05-22 09:37:06 +0000245 def list_shared_images(self, tenant_id):
246 """List shared images with the specified tenant"""
247 url = 'v1/shared-images/%s' % tenant_id
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500248 resp, body = self.get(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400249 self.expected_success(200, resp.status)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500250 body = json.loads(body)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000251 return service_client.ResponseBody(resp, body)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500252
Ghanshyam8b1603b2015-12-02 16:04:53 +0900253 def add_member(self, member_id, image_id, **kwargs):
254 """Add a member to an image.
255
256 Available params: see http://developer.openstack.org/
257 api-ref-image-v1.html#addMember-v1
258 """
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500259 url = 'v1/images/%s/members/%s' % (image_id, member_id)
Ghanshyam8b1603b2015-12-02 16:04:53 +0900260 body = json.dumps({'member': kwargs})
Valeriy Ponomaryov88686d82014-02-16 12:24:51 +0200261 resp, __ = self.put(url, body)
David Kranz9c3b3b62014-06-19 16:05:53 -0400262 self.expected_success(204, resp.status)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000263 return service_client.ResponseBody(resp)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500264
265 def delete_member(self, member_id, image_id):
266 url = 'v1/images/%s/members/%s' % (image_id, member_id)
267 resp, __ = self.delete(url)
David Kranz9c3b3b62014-06-19 16:05:53 -0400268 self.expected_success(204, resp.status)
Ken'ichi Ohmichia6ac2422015-01-13 01:09:39 +0000269 return service_client.ResponseBody(resp)
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500270
Attila Fazekasa8b5fe72013-08-01 16:59:06 +0200271 # NOTE(afazekas): just for the wait function
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100272 def _get_image_status(self, image_id):
David Kranz34f18782015-01-06 13:43:55 -0500273 meta = self.get_image_meta(image_id)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100274 status = meta['status']
275 return status
276
Attila Fazekasa8b5fe72013-08-01 16:59:06 +0200277 # NOTE(afazkas): Wait reinvented again. It is not in the correct layer
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100278 def wait_for_image_status(self, image_id, status):
279 """Waits for a Image to reach a given status."""
280 start_time = time.time()
281 old_value = value = self._get_image_status(image_id)
282 while True:
283 dtime = time.time() - start_time
284 time.sleep(self.build_interval)
285 if value != old_value:
286 LOG.info('Value transition from "%s" to "%s"'
287 'in %d second(s).', old_value,
288 value, dtime)
Attila Fazekas195f1d42013-10-24 10:33:16 +0200289 if value == status:
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100290 return value
291
Attila Fazekas195f1d42013-10-24 10:33:16 +0200292 if value == 'killed':
293 raise exceptions.ImageKilledException(image_id=image_id,
Attila Fazekas9dfb9072013-11-13 16:45:36 +0100294 status=status)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100295 if dtime > self.build_timeout:
296 message = ('Time Limit Exceeded! (%ds)'
297 'while waiting for %s, '
298 'but we got %s.' %
299 (self.build_timeout, status, value))
Matt Riedemann7cec3462014-06-25 12:48:43 -0700300 caller = misc_utils.find_test_caller()
301 if caller:
302 message = '(%s) %s' % (caller, message)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100303 raise exceptions.TimeoutException(message)
304 time.sleep(self.build_interval)
305 old_value = value
306 value = self._get_image_status(image_id)