blob: 37370b1fb71c425f1419be4e7947c457cd76535d [file] [log] [blame]
Kurt Taylor6a6f5be2013-04-02 18:53:47 -04001# Copyright 2012 IBM Corp.
Matthew Treinish9854d5b2012-09-20 10:22:13 -04002# 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 time
Matthew Treinish26dd0fa2012-12-04 17:14:37 -050017import urllib
Matthew Treinish9854d5b2012-09-20 10:22:13 -040018
19from lxml import etree
20
21from tempest.common.rest_client import RestClientXML
22from tempest import exceptions
Matthew Treinisha83a16e2012-12-07 13:44:02 -050023from tempest.services.compute.xml.common import Document
dwallecke62b9f02012-10-10 23:34:42 -050024from tempest.services.compute.xml.common import Element
25from tempest.services.compute.xml.common import Text
Matthew Treinisha83a16e2012-12-07 13:44:02 -050026from tempest.services.compute.xml.common import xml_to_json
27from tempest.services.compute.xml.common import XMLNS_11
Matthew Treinish9854d5b2012-09-20 10:22:13 -040028
29
30class VolumesClientXML(RestClientXML):
31 """
32 Client class to send CRUD Volume API requests to a Cinder endpoint
33 """
34
35 def __init__(self, config, username, password, auth_url, tenant_name=None):
36 super(VolumesClientXML, self).__init__(config, username, password,
37 auth_url, tenant_name)
Attila Fazekas786236c2013-01-31 16:06:51 +010038 self.service = self.config.volume.catalog_type
Matthew Treinish9854d5b2012-09-20 10:22:13 -040039 self.build_interval = self.config.compute.build_interval
40 self.build_timeout = self.config.compute.build_timeout
41
42 def _parse_volume(self, body):
43 vol = dict((attr, body.get(attr)) for attr in body.keys())
44
45 for child in body.getchildren():
46 tag = child.tag
47 if tag.startswith("{"):
48 ns, tag = tag.split("}", 1)
49 if tag == 'metadata':
50 vol['metadata'] = dict((meta.get('key'),
Attila Fazekas786236c2013-01-31 16:06:51 +010051 meta.text) for meta in
52 child.getchildren())
Matthew Treinish9854d5b2012-09-20 10:22:13 -040053 else:
54 vol[tag] = xml_to_json(child)
Attila Fazekas786236c2013-01-31 16:06:51 +010055 return vol
Matthew Treinish9854d5b2012-09-20 10:22:13 -040056
anju tiwari789449a2013-08-29 16:56:17 +053057 def get_attachment_from_volume(self, volume):
58 """Return the element 'attachment' from input volumes."""
59 return volume['attachments']['attachment']
60
Nayna Patel5e76be12013-08-19 12:10:16 +000061 def _check_if_bootable(self, volume):
62 """
63 Check if the volume is bootable, also change the value
64 of 'bootable' from string to boolean.
65 """
John Griffithf55f69e2013-09-19 14:10:57 -060066
67 # NOTE(jdg): Version 1 of Cinder API uses lc strings
68 # We should consider being explicit in this check to
69 # avoid introducing bugs like: LP #1227837
70
71 if volume['bootable'].lower() == 'true':
Nayna Patel5e76be12013-08-19 12:10:16 +000072 volume['bootable'] = True
John Griffithf55f69e2013-09-19 14:10:57 -060073 elif volume['bootable'].lower() == 'false':
Nayna Patel5e76be12013-08-19 12:10:16 +000074 volume['bootable'] = False
75 else:
76 raise ValueError(
77 'bootable flag is supposed to be either True or False,'
78 'it is %s' % volume['bootable'])
79 return volume
80
Matthew Treinish9854d5b2012-09-20 10:22:13 -040081 def list_volumes(self, params=None):
Sean Daguef237ccb2013-01-04 15:19:14 -050082 """List all the volumes created."""
Matthew Treinish9854d5b2012-09-20 10:22:13 -040083 url = 'volumes'
84
85 if params:
86 url += '?%s' % urllib.urlencode(params)
87
88 resp, body = self.get(url, self.headers)
89 body = etree.fromstring(body)
90 volumes = []
91 if body is not None:
92 volumes += [self._parse_volume(vol) for vol in list(body)]
Nayna Patel5e76be12013-08-19 12:10:16 +000093 for v in volumes:
94 v = self._check_if_bootable(v)
Matthew Treinish9854d5b2012-09-20 10:22:13 -040095 return resp, volumes
96
97 def list_volumes_with_detail(self, params=None):
Sean Daguef237ccb2013-01-04 15:19:14 -050098 """List all the details of volumes."""
Matthew Treinish9854d5b2012-09-20 10:22:13 -040099 url = 'volumes/detail'
100
101 if params:
102 url += '?%s' % urllib.urlencode(params)
103
104 resp, body = self.get(url, self.headers)
105 body = etree.fromstring(body)
106 volumes = []
107 if body is not None:
108 volumes += [self._parse_volume(vol) for vol in list(body)]
Nayna Patel5e76be12013-08-19 12:10:16 +0000109 for v in volumes:
110 v = self._check_if_bootable(v)
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400111 return resp, volumes
112
Attila Fazekasb8aa7592013-01-26 01:25:45 +0100113 def get_volume(self, volume_id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500114 """Returns the details of a single volume."""
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400115 url = "volumes/%s" % str(volume_id)
Attila Fazekasb8aa7592013-01-26 01:25:45 +0100116 resp, body = self.get(url, self.headers)
Nayna Patel5e76be12013-08-19 12:10:16 +0000117 body = self._parse_volume(etree.fromstring(body))
118 body = self._check_if_bootable(body)
119 return resp, body
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400120
Attila Fazekas786236c2013-01-31 16:06:51 +0100121 def create_volume(self, size, **kwargs):
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400122 """Creates a new Volume.
123
124 :param size: Size of volume in GB. (Required)
125 :param display_name: Optional Volume Name.
126 :param metadata: An optional dictionary of values for metadata.
Attila Fazekas786236c2013-01-31 16:06:51 +0100127 :param volume_type: Optional Name of volume_type for the volume
128 :param snapshot_id: When specified the volume is created from
129 this snapshot
Giulio Fidente36836c42013-04-05 15:43:51 +0200130 :param imageRef: When specified the volume is created from this
131 image
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400132 """
Attila Fazekasa8b5fe72013-08-01 16:59:06 +0200133 # NOTE(afazekas): it should use a volume namespace
Zhongyue Luoe0884a32012-09-25 17:24:17 +0800134 volume = Element("volume", xmlns=XMLNS_11, size=size)
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400135
Attila Fazekas786236c2013-01-31 16:06:51 +0100136 if 'metadata' in kwargs:
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400137 _metadata = Element('metadata')
138 volume.append(_metadata)
Attila Fazekas786236c2013-01-31 16:06:51 +0100139 for key, value in kwargs['metadata'].items():
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400140 meta = Element('meta')
141 meta.add_attr('key', key)
142 meta.append(Text(value))
143 _metadata.append(meta)
Attila Fazekas786236c2013-01-31 16:06:51 +0100144 attr_to_add = kwargs.copy()
145 del attr_to_add['metadata']
146 else:
147 attr_to_add = kwargs
148
149 for key, value in attr_to_add.items():
150 volume.add_attr(key, value)
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400151
152 resp, body = self.post('volumes', str(Document(volume)),
153 self.headers)
154 body = xml_to_json(etree.fromstring(body))
155 return resp, body
156
QingXin Meng611768a2013-09-18 00:51:33 -0700157 def update_volume(self, volume_id, **kwargs):
158 """Updates the Specified Volume."""
159 put_body = Element("volume", xmlns=XMLNS_11, **kwargs)
160
161 resp, body = self.put('volumes/%s' % volume_id,
162 str(Document(put_body)),
163 self.headers)
164 body = xml_to_json(etree.fromstring(body))
165 return resp, body
166
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400167 def delete_volume(self, volume_id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500168 """Deletes the Specified Volume."""
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400169 return self.delete("volumes/%s" % str(volume_id))
170
171 def wait_for_volume_status(self, volume_id, status):
Sean Daguef237ccb2013-01-04 15:19:14 -0500172 """Waits for a Volume to reach a given status."""
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400173 resp, body = self.get_volume(volume_id)
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400174 volume_status = body['status']
175 start = int(time.time())
176
177 while volume_status != status:
178 time.sleep(self.build_interval)
179 resp, body = self.get_volume(volume_id)
180 volume_status = body['status']
181 if volume_status == 'error':
182 raise exceptions.VolumeBuildErrorException(volume_id=volume_id)
183
184 if int(time.time()) - start >= self.build_timeout:
185 message = 'Volume %s failed to reach %s status within '\
Attila Fazekas786236c2013-01-31 16:06:51 +0100186 'the required time (%s s).' % (volume_id,
187 status,
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400188 self.build_timeout)
189 raise exceptions.TimeoutException(message)
190
191 def is_resource_deleted(self, id):
192 try:
Attila Fazekasf53172c2013-01-26 01:04:42 +0100193 self.get_volume(id)
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400194 except exceptions.NotFound:
195 return True
196 return False
anju tiwari789449a2013-08-29 16:56:17 +0530197
198 def attach_volume(self, volume_id, instance_uuid, mountpoint):
199 """Attaches a volume to a given instance on a given mountpoint."""
200 post_body = Element("os-attach",
201 instance_uuid=instance_uuid,
202 mountpoint=mountpoint
203 )
204 url = 'volumes/%s/action' % str(volume_id)
205 resp, body = self.post(url, str(Document(post_body)), self.headers)
206 if body:
207 body = xml_to_json(etree.fromstring(body))
208 return resp, body
209
210 def detach_volume(self, volume_id):
211 """Detaches a volume from an instance."""
212 post_body = Element("os-detach")
213 url = 'volumes/%s/action' % str(volume_id)
214 resp, body = self.post(url, str(Document(post_body)), self.headers)
215 if body:
216 body = xml_to_json(etree.fromstring(body))
217 return resp, body
218
Ryan Hsua67f4632013-08-29 16:03:06 -0700219 def upload_volume(self, volume_id, image_name, disk_format):
anju tiwari789449a2013-08-29 16:56:17 +0530220 """Uploads a volume in Glance."""
221 post_body = Element("os-volume_upload_image",
Ryan Hsua67f4632013-08-29 16:03:06 -0700222 image_name=image_name,
223 disk_format=disk_format)
anju tiwari789449a2013-08-29 16:56:17 +0530224 url = 'volumes/%s/action' % str(volume_id)
225 resp, body = self.post(url, str(Document(post_body)), self.headers)
226 volume = xml_to_json(etree.fromstring(body))
227 return resp, volume
wanghao5b981752013-10-22 11:41:41 +0800228
229 def extend_volume(self, volume_id, extend_size):
230 """Extend a volume."""
231 post_body = Element("os-extend",
232 new_size=extend_size)
233 url = 'volumes/%s/action' % str(volume_id)
234 resp, body = self.post(url, str(Document(post_body)), self.headers)
235 if body:
236 body = xml_to_json(etree.fromstring(body))
237 return resp, body
wanghaoaa1f2f92013-10-10 11:30:37 +0800238
239 def reset_volume_status(self, volume_id, status):
240 """Reset the Specified Volume's Status."""
241 post_body = Element("os-reset_status",
242 status=status
243 )
244 url = 'volumes/%s/action' % str(volume_id)
245 resp, body = self.post(url, str(Document(post_body)), self.headers)
246 if body:
247 body = xml_to_json(etree.fromstring(body))
248 return resp, body
249
250 def volume_begin_detaching(self, volume_id):
251 """Volume Begin Detaching."""
252 post_body = Element("os-begin_detaching")
253 url = 'volumes/%s/action' % str(volume_id)
254 resp, body = self.post(url, str(Document(post_body)), self.headers)
255 if body:
256 body = xml_to_json(etree.fromstring(body))
257 return resp, body
258
259 def volume_roll_detaching(self, volume_id):
260 """Volume Roll Detaching."""
261 post_body = Element("os-roll_detaching")
262 url = 'volumes/%s/action' % str(volume_id)
263 resp, body = self.post(url, str(Document(post_body)), self.headers)
264 if body:
265 body = xml_to_json(etree.fromstring(body))
266 return resp, body
zhangyanzi6b632432013-10-24 19:08:50 +0800267
268 def reserve_volume(self, volume_id):
269 """Reserves a volume."""
270 post_body = Element("os-reserve")
271 url = 'volumes/%s/action' % str(volume_id)
272 resp, body = self.post(url, str(Document(post_body)), self.headers)
273 if body:
274 body = xml_to_json(etree.fromstring(body))
275 return resp, body
276
277 def unreserve_volume(self, volume_id):
278 """Restore a reserved volume ."""
279 post_body = Element("os-unreserve")
280 url = 'volumes/%s/action' % str(volume_id)
281 resp, body = self.post(url, str(Document(post_body)), self.headers)
282 if body:
283 body = xml_to_json(etree.fromstring(body))
284 return resp, body
wingwjcbd82dc2013-10-22 16:38:39 +0800285
286 def create_volume_transfer(self, vol_id, display_name=None):
287 """Create a volume transfer."""
288 post_body = Element("transfer",
289 volume_id=vol_id)
290 if display_name:
291 post_body.add_attr('name', display_name)
292 resp, body = self.post('os-volume-transfer',
293 str(Document(post_body)),
294 self.headers)
295 volume = xml_to_json(etree.fromstring(body))
296 return resp, volume
297
298 def get_volume_transfer(self, transfer_id):
299 """Returns the details of a volume transfer."""
300 url = "os-volume-transfer/%s" % str(transfer_id)
301 resp, body = self.get(url, self.headers)
302 volume = xml_to_json(etree.fromstring(body))
303 return resp, volume
304
305 def list_volume_transfers(self, params=None):
306 """List all the volume transfers created."""
307 url = 'os-volume-transfer'
308 if params:
309 url += '?%s' % urllib.urlencode(params)
310
311 resp, body = self.get(url, self.headers)
312 body = etree.fromstring(body)
313 volumes = []
314 if body is not None:
315 volumes += [self._parse_volume_transfer(vol) for vol in list(body)]
316 return resp, volumes
317
318 def _parse_volume_transfer(self, body):
319 vol = dict((attr, body.get(attr)) for attr in body.keys())
320 for child in body.getchildren():
321 tag = child.tag
322 if tag.startswith("{"):
323 tag = tag.split("}", 1)
324 vol[tag] = xml_to_json(child)
325 return vol
326
327 def delete_volume_transfer(self, transfer_id):
328 """Delete a volume transfer."""
329 return self.delete("os-volume-transfer/%s" % str(transfer_id))
330
331 def accept_volume_transfer(self, transfer_id, transfer_auth_key):
332 """Accept a volume transfer."""
333 post_body = Element("accept", auth_key=transfer_auth_key)
334 url = 'os-volume-transfer/%s/accept' % transfer_id
335 resp, body = self.post(url, str(Document(post_body)), self.headers)
336 volume = xml_to_json(etree.fromstring(body))
337 return resp, volume
zhangyanziaa180072013-11-21 12:31:26 +0800338
339 def update_volume_readonly(self, volume_id, readonly):
340 """Update the Specified Volume readonly."""
341 post_body = Element("os-update_readonly_flag",
342 readonly=readonly)
343 url = 'volumes/%s/action' % str(volume_id)
344 resp, body = self.post(url, str(Document(post_body)), self.headers)
345 if body:
346 body = xml_to_json(etree.fromstring(body))
347 return resp, body
wanghao9d3d6cb2013-11-12 15:10:10 +0800348
349 def force_delete_volume(self, volume_id):
350 """Force Delete Volume."""
351 post_body = Element("os-force_delete")
352 url = 'volumes/%s/action' % str(volume_id)
353 resp, body = self.post(url, str(Document(post_body)), self.headers)
354 if body:
355 body = xml_to_json(etree.fromstring(body))
356 return resp, body
huangtianhua0ff41682013-12-16 14:49:31 +0800357
358 def _metadata_body(self, meta):
359 post_body = Element('metadata')
360 for k, v in meta.items():
361 data = Element('meta', key=k)
362 data.append(Text(v))
363 post_body.append(data)
364 return post_body
365
366 def _parse_key_value(self, node):
367 """Parse <foo key='key'>value</foo> data into {'key': 'value'}."""
368 data = {}
369 for node in node.getchildren():
370 data[node.get('key')] = node.text
371 return data
372
373 def create_volume_metadata(self, volume_id, metadata):
374 """Create metadata for the volume."""
375 post_body = self._metadata_body(metadata)
376 resp, body = self.post('volumes/%s/metadata' % volume_id,
377 str(Document(post_body)),
378 self.headers)
379 body = self._parse_key_value(etree.fromstring(body))
380 return resp, body
381
382 def get_volume_metadata(self, volume_id):
383 """Get metadata of the volume."""
384 url = "volumes/%s/metadata" % str(volume_id)
385 resp, body = self.get(url, self.headers)
386 body = self._parse_key_value(etree.fromstring(body))
387 return resp, body
388
389 def update_volume_metadata(self, volume_id, metadata):
390 """Update metadata for the volume."""
391 put_body = self._metadata_body(metadata)
392 url = "volumes/%s/metadata" % str(volume_id)
393 resp, body = self.put(url, str(Document(put_body)), self.headers)
394 body = self._parse_key_value(etree.fromstring(body))
395 return resp, body
396
397 def update_volume_metadata_item(self, volume_id, id, meta_item):
398 """Update metadata item for the volume."""
399 for k, v in meta_item.items():
400 put_body = Element('meta', key=k)
401 put_body.append(Text(v))
402 url = "volumes/%s/metadata/%s" % (str(volume_id), str(id))
403 resp, body = self.put(url, str(Document(put_body)), self.headers)
404 body = xml_to_json(etree.fromstring(body))
405 return resp, body
406
407 def delete_volume_metadata_item(self, volume_id, id):
408 """Delete metadata item for the volume."""
409 url = "volumes/%s/metadata/%s" % (str(volume_id), str(id))
410 return self.delete(url)