blob: 61dd050964f342d01aa41bd3d82838c819843982 [file] [log] [blame]
Matthew Treinish72ea4422013-02-07 14:42:49 -05001# vim: tabstop=4 shiftwidth=4 softtabstop=4
2#
Kurt Taylor6a6f5be2013-04-02 18:53:47 -04003# Copyright 2013 IBM Corp.
Matthew Treinish72ea4422013-02-07 14:42:49 -05004# All Rights Reserved.
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License. You may obtain
8# a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15# License for the specific language governing permissions and limitations
16# under the License.
17
18import copy
Attila Fazekas5c068812013-02-14 15:29:44 +010019import errno
Matthew Treinish72ea4422013-02-07 14:42:49 -050020import json
21import os
Attila Fazekase72b7cd2013-03-26 18:34:21 +010022import time
Matthew Treinish72ea4422013-02-07 14:42:49 -050023import urllib
24
25from tempest.common import glance_http
26from tempest.common.rest_client import RestClient
27from tempest import exceptions
Matthew Treinishf4a9b0f2013-07-26 16:58:26 -040028from tempest.openstack.common import log as logging
Matthew Treinish72ea4422013-02-07 14:42:49 -050029
Attila Fazekase72b7cd2013-03-26 18:34:21 +010030LOG = logging.getLogger(__name__)
31
Matthew Treinish72ea4422013-02-07 14:42:49 -050032
33class ImageClientJSON(RestClient):
34
35 def __init__(self, config, username, password, auth_url, tenant_name=None):
36 super(ImageClientJSON, self).__init__(config, username, password,
37 auth_url, tenant_name)
38 self.service = self.config.images.catalog_type
Matthew Treinish406da272013-12-12 16:42:31 +000039 if config.service_available.glance:
40 self.http = self._get_http()
Matthew Treinish72ea4422013-02-07 14:42:49 -050041
42 def _image_meta_from_headers(self, headers):
43 meta = {'properties': {}}
44 for key, value in headers.iteritems():
45 if key.startswith('x-image-meta-property-'):
46 _key = key[22:]
47 meta['properties'][_key] = value
48 elif key.startswith('x-image-meta-'):
49 _key = key[13:]
50 meta[_key] = value
51
52 for key in ['is_public', 'protected', 'deleted']:
53 if key in meta:
54 meta[key] = meta[key].strip().lower() in ('t', 'true', 'yes',
55 '1')
56 for key in ['size', 'min_ram', 'min_disk']:
57 if key in meta:
58 try:
59 meta[key] = int(meta[key])
60 except ValueError:
61 pass
62 return meta
63
64 def _image_meta_to_headers(self, fields):
65 headers = {}
66 fields_copy = copy.deepcopy(fields)
Attila Fazekase72b7cd2013-03-26 18:34:21 +010067 copy_from = fields_copy.pop('copy_from', None)
68 if copy_from is not None:
69 headers['x-glance-api-copy-from'] = copy_from
Matthew Treinish72ea4422013-02-07 14:42:49 -050070 for key, value in fields_copy.pop('properties', {}).iteritems():
71 headers['x-image-meta-property-%s' % key] = str(value)
Attila Fazekase72b7cd2013-03-26 18:34:21 +010072 for key, value in fields_copy.pop('api', {}).iteritems():
73 headers['x-glance-api-property-%s' % key] = str(value)
Matthew Treinish72ea4422013-02-07 14:42:49 -050074 for key, value in fields_copy.iteritems():
75 headers['x-image-meta-%s' % key] = str(value)
76 return headers
77
78 def _get_file_size(self, obj):
79 """Analyze file-like object and attempt to determine its size.
80
81 :param obj: file-like object, typically redirected from stdin.
82 :retval The file's size or None if it cannot be determined.
83 """
84 # For large images, we need to supply the size of the
85 # image file. See LP Bugs #827660 and #845788.
86 if hasattr(obj, 'seek') and hasattr(obj, 'tell'):
87 try:
88 obj.seek(0, os.SEEK_END)
89 obj_size = obj.tell()
90 obj.seek(0)
91 return obj_size
Dirk Mueller1db5db22013-06-23 20:21:32 +020092 except IOError as e:
Matthew Treinish72ea4422013-02-07 14:42:49 -050093 if e.errno == errno.ESPIPE:
94 # Illegal seek. This means the user is trying
95 # to pipe image data to the client, e.g.
96 # echo testdata | bin/glance add blah..., or
97 # that stdin is empty, or that a file-like
98 # object which doesn't support 'seek/tell' has
99 # been supplied.
100 return None
101 else:
102 raise
103 else:
104 # Cannot determine size of input image
105 return None
106
107 def _get_http(self):
Matthew Treinish801f3aa2013-02-28 15:35:03 -0500108 token, endpoint = self.keystone_auth(self.user,
109 self.password,
110 self.auth_url,
111 self.service,
112 self.tenant_name)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500113 dscv = self.config.identity.disable_ssl_certificate_validation
114 return glance_http.HTTPClient(endpoint=endpoint, token=token,
115 insecure=dscv)
116
117 def _create_with_data(self, headers, data):
118 resp, body_iter = self.http.raw_request('POST', '/v1/images',
119 headers=headers, body=data)
120 self._error_checker('POST', '/v1/images', headers, data, resp,
121 body_iter)
122 body = json.loads(''.join([c for c in body_iter]))
123 return resp, body['image']
124
125 def _update_with_data(self, image_id, headers, data):
126 url = '/v1/images/%s' % image_id
127 resp, body_iter = self.http.raw_request('PUT', url, headers=headers,
128 body=data)
129 self._error_checker('PUT', url, headers, data,
130 resp, body_iter)
131 body = json.loads(''.join([c for c in body_iter]))
132 return resp, body['image']
133
Matthew Treinishce3ef922013-03-11 14:02:46 -0400134 def create_image(self, name, container_format, disk_format, **kwargs):
Matthew Treinish72ea4422013-02-07 14:42:49 -0500135 params = {
136 "name": name,
137 "container_format": container_format,
138 "disk_format": disk_format,
Matthew Treinish72ea4422013-02-07 14:42:49 -0500139 }
Matthew Treinishce3ef922013-03-11 14:02:46 -0400140
Matthew Treinish72ea4422013-02-07 14:42:49 -0500141 headers = {}
142
hi2suresh75a20302013-04-09 09:17:06 +0000143 for option in ['is_public', 'location', 'properties',
144 'copy_from', 'min_ram']:
Matthew Treinishce3ef922013-03-11 14:02:46 -0400145 if option in kwargs:
146 params[option] = kwargs.get(option)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500147
148 headers.update(self._image_meta_to_headers(params))
149
Matthew Treinishce3ef922013-03-11 14:02:46 -0400150 if 'data' in kwargs:
151 return self._create_with_data(headers, kwargs.get('data'))
Matthew Treinish72ea4422013-02-07 14:42:49 -0500152
Matthew Treinishce3ef922013-03-11 14:02:46 -0400153 resp, body = self.post('v1/images', None, headers)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500154 body = json.loads(body)
155 return resp, body['image']
156
157 def update_image(self, image_id, name=None, container_format=None,
158 data=None):
159 params = {}
160 headers = {}
161 if name is not None:
162 params['name'] = name
163
164 if container_format is not None:
165 params['container_format'] = container_format
166
167 headers.update(self._image_meta_to_headers(params))
168
169 if data is not None:
170 return self._update_with_data(image_id, headers, data)
171
172 url = 'v1/images/%s' % image_id
173 resp, body = self.put(url, data, headers)
174 body = json.loads(body)
175 return resp, body['image']
176
177 def delete_image(self, image_id):
178 url = 'v1/images/%s' % image_id
ivan-zhu8f992be2013-07-31 14:56:58 +0800179 return self.delete(url)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500180
Attila Fazekas11795b52013-02-24 15:49:08 +0100181 def image_list(self, **kwargs):
Matthew Treinish72ea4422013-02-07 14:42:49 -0500182 url = 'v1/images'
183
Attila Fazekas11795b52013-02-24 15:49:08 +0100184 if len(kwargs) > 0:
185 url += '?%s' % urllib.urlencode(kwargs)
186
187 resp, body = self.get(url)
188 body = json.loads(body)
189 return resp, body['images']
190
ivan-zhuccc89462013-10-31 16:53:12 +0800191 def image_list_detail(self, properties=dict(), **kwargs):
Attila Fazekas11795b52013-02-24 15:49:08 +0100192 url = 'v1/images/detail'
193
ivan-zhuccc89462013-10-31 16:53:12 +0800194 params = {}
195 for key, value in properties.items():
196 params['property-%s' % key] = value
197
198 kwargs.update(params)
199
Attila Fazekas11795b52013-02-24 15:49:08 +0100200 if len(kwargs) > 0:
201 url += '?%s' % urllib.urlencode(kwargs)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500202
203 resp, body = self.get(url)
204 body = json.loads(body)
205 return resp, body['images']
206
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100207 def get_image_meta(self, image_id):
208 url = 'v1/images/%s' % image_id
209 resp, __ = self.head(url)
210 body = self._image_meta_from_headers(resp)
211 return resp, body
212
Attila Fazekasb8aa7592013-01-26 01:25:45 +0100213 def get_image(self, image_id):
Matthew Treinish72ea4422013-02-07 14:42:49 -0500214 url = 'v1/images/%s' % image_id
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100215 resp, body = self.get(url)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500216 return resp, body
217
218 def is_resource_deleted(self, id):
219 try:
Attila Fazekasb8aa7592013-01-26 01:25:45 +0100220 self.get_image(id)
Matthew Treinish72ea4422013-02-07 14:42:49 -0500221 except exceptions.NotFound:
222 return True
223 return False
Matthew Treinishfa23cf82013-03-06 14:23:02 -0500224
225 def get_image_membership(self, image_id):
226 url = 'v1/images/%s/members' % image_id
227 resp, body = self.get(url)
228 body = json.loads(body)
229 return resp, body
230
231 def get_shared_images(self, member_id):
232 url = 'v1/shared-images/%s' % member_id
233 resp, body = self.get(url)
234 body = json.loads(body)
235 return resp, body
236
237 def add_member(self, member_id, image_id, can_share=False):
238 url = 'v1/images/%s/members/%s' % (image_id, member_id)
239 body = None
240 if can_share:
241 body = json.dumps({'member': {'can_share': True}})
242 resp, __ = self.put(url, body, self.headers)
243 return resp
244
245 def delete_member(self, member_id, image_id):
246 url = 'v1/images/%s/members/%s' % (image_id, member_id)
247 resp, __ = self.delete(url)
248 return resp
249
250 def replace_membership_list(self, image_id, member_list):
251 url = 'v1/images/%s/members' % image_id
252 body = json.dumps({'membership': member_list})
253 resp, data = self.put(url, body, self.headers)
254 data = json.loads(data)
255 return resp, data
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100256
Attila Fazekasa8b5fe72013-08-01 16:59:06 +0200257 # NOTE(afazekas): just for the wait function
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100258 def _get_image_status(self, image_id):
259 resp, meta = self.get_image_meta(image_id)
260 status = meta['status']
261 return status
262
Attila Fazekasa8b5fe72013-08-01 16:59:06 +0200263 # NOTE(afazkas): Wait reinvented again. It is not in the correct layer
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100264 def wait_for_image_status(self, image_id, status):
265 """Waits for a Image to reach a given status."""
266 start_time = time.time()
267 old_value = value = self._get_image_status(image_id)
268 while True:
269 dtime = time.time() - start_time
270 time.sleep(self.build_interval)
271 if value != old_value:
272 LOG.info('Value transition from "%s" to "%s"'
273 'in %d second(s).', old_value,
274 value, dtime)
Attila Fazekas195f1d42013-10-24 10:33:16 +0200275 if value == status:
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100276 return value
277
Attila Fazekas195f1d42013-10-24 10:33:16 +0200278 if value == 'killed':
279 raise exceptions.ImageKilledException(image_id=image_id,
Attila Fazekas9dfb9072013-11-13 16:45:36 +0100280 status=status)
Attila Fazekase72b7cd2013-03-26 18:34:21 +0100281 if dtime > self.build_timeout:
282 message = ('Time Limit Exceeded! (%ds)'
283 'while waiting for %s, '
284 'but we got %s.' %
285 (self.build_timeout, status, value))
286 raise exceptions.TimeoutException(message)
287 time.sleep(self.build_interval)
288 old_value = value
289 value = self._get_image_status(image_id)