blob: b59ec039dce31411c414d1797da9845d3a4e1fc1 [file] [log] [blame]
Matthew Treinish9854d5b2012-09-20 10:22:13 -04001# vim: tabstop=4 shiftwidth=4 softtabstop=4
2#
Kurt Taylor6a6f5be2013-04-02 18:53:47 -04003# Copyright 2012 IBM Corp.
Matthew Treinish9854d5b2012-09-20 10:22:13 -04004# 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 time
Matthew Treinish26dd0fa2012-12-04 17:14:37 -050019import urllib
Matthew Treinish9854d5b2012-09-20 10:22:13 -040020
21from lxml import etree
22
23from tempest.common.rest_client import RestClientXML
24from tempest import exceptions
Matthew Treinisha83a16e2012-12-07 13:44:02 -050025from tempest.services.compute.xml.common import Document
dwallecke62b9f02012-10-10 23:34:42 -050026from tempest.services.compute.xml.common import Element
27from tempest.services.compute.xml.common import Text
Matthew Treinisha83a16e2012-12-07 13:44:02 -050028from tempest.services.compute.xml.common import xml_to_json
29from tempest.services.compute.xml.common import XMLNS_11
Matthew Treinish9854d5b2012-09-20 10:22:13 -040030
31
32class VolumesClientXML(RestClientXML):
33 """
34 Client class to send CRUD Volume API requests to a Cinder endpoint
35 """
36
37 def __init__(self, config, username, password, auth_url, tenant_name=None):
38 super(VolumesClientXML, self).__init__(config, username, password,
39 auth_url, tenant_name)
Attila Fazekas786236c2013-01-31 16:06:51 +010040 self.service = self.config.volume.catalog_type
Matthew Treinish9854d5b2012-09-20 10:22:13 -040041 self.build_interval = self.config.compute.build_interval
42 self.build_timeout = self.config.compute.build_timeout
43
44 def _parse_volume(self, body):
45 vol = dict((attr, body.get(attr)) for attr in body.keys())
46
47 for child in body.getchildren():
48 tag = child.tag
49 if tag.startswith("{"):
50 ns, tag = tag.split("}", 1)
51 if tag == 'metadata':
52 vol['metadata'] = dict((meta.get('key'),
Attila Fazekas786236c2013-01-31 16:06:51 +010053 meta.text) for meta in
54 child.getchildren())
Matthew Treinish9854d5b2012-09-20 10:22:13 -040055 else:
56 vol[tag] = xml_to_json(child)
Attila Fazekas786236c2013-01-31 16:06:51 +010057 return vol
Matthew Treinish9854d5b2012-09-20 10:22:13 -040058
anju tiwari789449a2013-08-29 16:56:17 +053059 def get_attachment_from_volume(self, volume):
60 """Return the element 'attachment' from input volumes."""
61 return volume['attachments']['attachment']
62
Nayna Patel5e76be12013-08-19 12:10:16 +000063 def _check_if_bootable(self, volume):
64 """
65 Check if the volume is bootable, also change the value
66 of 'bootable' from string to boolean.
67 """
John Griffithf55f69e2013-09-19 14:10:57 -060068
69 # NOTE(jdg): Version 1 of Cinder API uses lc strings
70 # We should consider being explicit in this check to
71 # avoid introducing bugs like: LP #1227837
72
73 if volume['bootable'].lower() == 'true':
Nayna Patel5e76be12013-08-19 12:10:16 +000074 volume['bootable'] = True
John Griffithf55f69e2013-09-19 14:10:57 -060075 elif volume['bootable'].lower() == 'false':
Nayna Patel5e76be12013-08-19 12:10:16 +000076 volume['bootable'] = False
77 else:
78 raise ValueError(
79 'bootable flag is supposed to be either True or False,'
80 'it is %s' % volume['bootable'])
81 return volume
82
Matthew Treinish9854d5b2012-09-20 10:22:13 -040083 def list_volumes(self, params=None):
Sean Daguef237ccb2013-01-04 15:19:14 -050084 """List all the volumes created."""
Matthew Treinish9854d5b2012-09-20 10:22:13 -040085 url = 'volumes'
86
87 if params:
88 url += '?%s' % urllib.urlencode(params)
89
90 resp, body = self.get(url, self.headers)
91 body = etree.fromstring(body)
92 volumes = []
93 if body is not None:
94 volumes += [self._parse_volume(vol) for vol in list(body)]
Nayna Patel5e76be12013-08-19 12:10:16 +000095 for v in volumes:
96 v = self._check_if_bootable(v)
Matthew Treinish9854d5b2012-09-20 10:22:13 -040097 return resp, volumes
98
99 def list_volumes_with_detail(self, params=None):
Sean Daguef237ccb2013-01-04 15:19:14 -0500100 """List all the details of volumes."""
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400101 url = 'volumes/detail'
102
103 if params:
104 url += '?%s' % urllib.urlencode(params)
105
106 resp, body = self.get(url, self.headers)
107 body = etree.fromstring(body)
108 volumes = []
109 if body is not None:
110 volumes += [self._parse_volume(vol) for vol in list(body)]
Nayna Patel5e76be12013-08-19 12:10:16 +0000111 for v in volumes:
112 v = self._check_if_bootable(v)
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400113 return resp, volumes
114
Attila Fazekasb8aa7592013-01-26 01:25:45 +0100115 def get_volume(self, volume_id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500116 """Returns the details of a single volume."""
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400117 url = "volumes/%s" % str(volume_id)
Attila Fazekasb8aa7592013-01-26 01:25:45 +0100118 resp, body = self.get(url, self.headers)
Nayna Patel5e76be12013-08-19 12:10:16 +0000119 body = self._parse_volume(etree.fromstring(body))
120 body = self._check_if_bootable(body)
121 return resp, body
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400122
Attila Fazekas786236c2013-01-31 16:06:51 +0100123 def create_volume(self, size, **kwargs):
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400124 """Creates a new Volume.
125
126 :param size: Size of volume in GB. (Required)
127 :param display_name: Optional Volume Name.
128 :param metadata: An optional dictionary of values for metadata.
Attila Fazekas786236c2013-01-31 16:06:51 +0100129 :param volume_type: Optional Name of volume_type for the volume
130 :param snapshot_id: When specified the volume is created from
131 this snapshot
Giulio Fidente36836c42013-04-05 15:43:51 +0200132 :param imageRef: When specified the volume is created from this
133 image
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400134 """
Attila Fazekasa8b5fe72013-08-01 16:59:06 +0200135 # NOTE(afazekas): it should use a volume namespace
Zhongyue Luoe0884a32012-09-25 17:24:17 +0800136 volume = Element("volume", xmlns=XMLNS_11, size=size)
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400137
Attila Fazekas786236c2013-01-31 16:06:51 +0100138 if 'metadata' in kwargs:
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400139 _metadata = Element('metadata')
140 volume.append(_metadata)
Attila Fazekas786236c2013-01-31 16:06:51 +0100141 for key, value in kwargs['metadata'].items():
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400142 meta = Element('meta')
143 meta.add_attr('key', key)
144 meta.append(Text(value))
145 _metadata.append(meta)
Attila Fazekas786236c2013-01-31 16:06:51 +0100146 attr_to_add = kwargs.copy()
147 del attr_to_add['metadata']
148 else:
149 attr_to_add = kwargs
150
151 for key, value in attr_to_add.items():
152 volume.add_attr(key, value)
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400153
154 resp, body = self.post('volumes', str(Document(volume)),
155 self.headers)
156 body = xml_to_json(etree.fromstring(body))
157 return resp, body
158
QingXin Meng611768a2013-09-18 00:51:33 -0700159 def update_volume(self, volume_id, **kwargs):
160 """Updates the Specified Volume."""
161 put_body = Element("volume", xmlns=XMLNS_11, **kwargs)
162
163 resp, body = self.put('volumes/%s' % volume_id,
164 str(Document(put_body)),
165 self.headers)
166 body = xml_to_json(etree.fromstring(body))
167 return resp, body
168
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400169 def delete_volume(self, volume_id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500170 """Deletes the Specified Volume."""
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400171 return self.delete("volumes/%s" % str(volume_id))
172
173 def wait_for_volume_status(self, volume_id, status):
Sean Daguef237ccb2013-01-04 15:19:14 -0500174 """Waits for a Volume to reach a given status."""
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400175 resp, body = self.get_volume(volume_id)
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400176 volume_status = body['status']
177 start = int(time.time())
178
179 while volume_status != status:
180 time.sleep(self.build_interval)
181 resp, body = self.get_volume(volume_id)
182 volume_status = body['status']
183 if volume_status == 'error':
184 raise exceptions.VolumeBuildErrorException(volume_id=volume_id)
185
186 if int(time.time()) - start >= self.build_timeout:
187 message = 'Volume %s failed to reach %s status within '\
Attila Fazekas786236c2013-01-31 16:06:51 +0100188 'the required time (%s s).' % (volume_id,
189 status,
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400190 self.build_timeout)
191 raise exceptions.TimeoutException(message)
192
193 def is_resource_deleted(self, id):
194 try:
Attila Fazekasf53172c2013-01-26 01:04:42 +0100195 self.get_volume(id)
Matthew Treinish9854d5b2012-09-20 10:22:13 -0400196 except exceptions.NotFound:
197 return True
198 return False
anju tiwari789449a2013-08-29 16:56:17 +0530199
200 def attach_volume(self, volume_id, instance_uuid, mountpoint):
201 """Attaches a volume to a given instance on a given mountpoint."""
202 post_body = Element("os-attach",
203 instance_uuid=instance_uuid,
204 mountpoint=mountpoint
205 )
206 url = 'volumes/%s/action' % str(volume_id)
207 resp, body = self.post(url, str(Document(post_body)), self.headers)
208 if body:
209 body = xml_to_json(etree.fromstring(body))
210 return resp, body
211
212 def detach_volume(self, volume_id):
213 """Detaches a volume from an instance."""
214 post_body = Element("os-detach")
215 url = 'volumes/%s/action' % str(volume_id)
216 resp, body = self.post(url, str(Document(post_body)), self.headers)
217 if body:
218 body = xml_to_json(etree.fromstring(body))
219 return resp, body
220
Ryan Hsua67f4632013-08-29 16:03:06 -0700221 def upload_volume(self, volume_id, image_name, disk_format):
anju tiwari789449a2013-08-29 16:56:17 +0530222 """Uploads a volume in Glance."""
223 post_body = Element("os-volume_upload_image",
Ryan Hsua67f4632013-08-29 16:03:06 -0700224 image_name=image_name,
225 disk_format=disk_format)
anju tiwari789449a2013-08-29 16:56:17 +0530226 url = 'volumes/%s/action' % str(volume_id)
227 resp, body = self.post(url, str(Document(post_body)), self.headers)
228 volume = xml_to_json(etree.fromstring(body))
229 return resp, volume