blob: 626e655f6e9d9633f1a70629daae18a77a5a7e71 [file] [log] [blame]
Kurt Taylor6a6f5be2013-04-02 18:53:47 -04001# Copyright 2012 IBM Corp.
nithya-ganesane6a36c82013-02-15 14:38:27 +00002# Copyright 2013 Hewlett-Packard Development Company, L.P.
Dan Smithcf8fab62012-08-14 08:03:48 -07003# All Rights Reserved.
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License. You may obtain
7# a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
16
Matthew Treinisha83a16e2012-12-07 13:44:02 -050017import time
18import urllib
19
Dan Smithcf8fab62012-08-14 08:03:48 -070020from lxml import etree
Matthew Treinisha83a16e2012-12-07 13:44:02 -050021
vponomaryov960eeb42014-02-22 18:25:25 +020022from tempest.common import rest_client
Attila Fazekas0abbc952013-07-01 19:19:42 +020023from tempest.common import waiters
Matthew Treinish28f164c2014-03-04 18:55:06 +000024from tempest.common import xml_utils
Matthew Treinish684d8992014-01-30 16:27:40 +000025from tempest import config
Matthew Treinisha83a16e2012-12-07 13:44:02 -050026from tempest import exceptions
Matthew Treinishf4a9b0f2013-07-26 16:58:26 -040027from tempest.openstack.common import log as logging
Matthew Treinisha83a16e2012-12-07 13:44:02 -050028
Matthew Treinish684d8992014-01-30 16:27:40 +000029CONF = config.CONF
Dan Smithcf8fab62012-08-14 08:03:48 -070030
31LOG = logging.getLogger(__name__)
32
33
Jaroslav Henner93f19e82012-12-12 20:24:17 +010034def _translate_ip_xml_json(ip):
35 """
36 Convert the address version to int.
37 """
38 ip = dict(ip)
39 version = ip.get('version')
40 if version:
41 ip['version'] = int(version)
Mauro S. M. Rodriguesf5166402013-04-01 10:25:26 -040042 # NOTE(maurosr): just a fast way to avoid the xml version with the
43 # expanded xml namespace.
44 type_ns_prefix = ('{http://docs.openstack.org/compute/ext/extended_ips/'
45 'api/v1.1}type')
Attila Fazekasb3d707c2013-09-10 19:01:15 +020046 mac_ns_prefix = ('{http://docs.openstack.org/compute/ext/extended_ips_mac'
47 '/api/v1.1}mac_addr')
48
Mauro S. M. Rodriguesf5166402013-04-01 10:25:26 -040049 if type_ns_prefix in ip:
Attila Fazekasb3d707c2013-09-10 19:01:15 +020050 ip['OS-EXT-IPS:type'] = ip.pop(type_ns_prefix)
51
52 if mac_ns_prefix in ip:
53 ip['OS-EXT-IPS-MAC:mac_addr'] = ip.pop(mac_ns_prefix)
Jaroslav Henner93f19e82012-12-12 20:24:17 +010054 return ip
55
56
57def _translate_network_xml_to_json(network):
58 return [_translate_ip_xml_json(ip.attrib)
Matthew Treinish28f164c2014-03-04 18:55:06 +000059 for ip in network.findall('{%s}ip' % xml_utils.XMLNS_11)]
Jaroslav Henner93f19e82012-12-12 20:24:17 +010060
61
62def _translate_addresses_xml_to_json(xml_addresses):
63 return dict((network.attrib['id'], _translate_network_xml_to_json(network))
Matthew Treinish28f164c2014-03-04 18:55:06 +000064 for network in xml_addresses.findall('{%s}network' %
65 xml_utils.XMLNS_11))
Jaroslav Henner93f19e82012-12-12 20:24:17 +010066
67
68def _translate_server_xml_to_json(xml_dom):
Attila Fazekasb2902af2013-02-16 16:22:44 +010069 """Convert server XML to server JSON.
Jaroslav Henner93f19e82012-12-12 20:24:17 +010070
71 The addresses collection does not convert well by the dumb xml_to_json.
72 This method does some pre and post-processing to deal with that.
73
74 Translate XML addresses subtree to JSON.
75
76 Having xml_doc similar to
77 <api:server xmlns:api="http://docs.openstack.org/compute/api/v1.1">
78 <api:addresses>
79 <api:network id="foo_novanetwork">
80 <api:ip version="4" addr="192.168.0.4"/>
81 </api:network>
82 <api:network id="bar_novanetwork">
83 <api:ip version="4" addr="10.1.0.4"/>
84 <api:ip version="6" addr="2001:0:0:1:2:3:4:5"/>
85 </api:network>
86 </api:addresses>
87 </api:server>
88
89 the _translate_server_xml_to_json(etree.fromstring(xml_doc)) should produce
90 something like
91
92 {'addresses': {'bar_novanetwork': [{'addr': '10.1.0.4', 'version': 4},
93 {'addr': '2001:0:0:1:2:3:4:5',
94 'version': 6}],
95 'foo_novanetwork': [{'addr': '192.168.0.4', 'version': 4}]}}
96 """
Matthew Treinish28f164c2014-03-04 18:55:06 +000097 nsmap = {'api': xml_utils.XMLNS_11}
Jaroslav Henner93f19e82012-12-12 20:24:17 +010098 addresses = xml_dom.xpath('/api:server/api:addresses', namespaces=nsmap)
99 if addresses:
100 if len(addresses) > 1:
101 raise ValueError('Expected only single `addresses` element.')
102 json_addresses = _translate_addresses_xml_to_json(addresses[0])
Matthew Treinish28f164c2014-03-04 18:55:06 +0000103 json = xml_utils.xml_to_json(xml_dom)
Jaroslav Henner93f19e82012-12-12 20:24:17 +0100104 json['addresses'] = json_addresses
105 else:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000106 json = xml_utils.xml_to_json(xml_dom)
Attila Fazekasb3d707c2013-09-10 19:01:15 +0200107 diskConfig = ('{http://docs.openstack.org'
108 '/compute/ext/disk_config/api/v1.1}diskConfig')
109 terminated_at = ('{http://docs.openstack.org/'
110 'compute/ext/server_usage/api/v1.1}terminated_at')
111 launched_at = ('{http://docs.openstack.org'
112 '/compute/ext/server_usage/api/v1.1}launched_at')
113 power_state = ('{http://docs.openstack.org'
114 '/compute/ext/extended_status/api/v1.1}power_state')
115 availability_zone = ('{http://docs.openstack.org'
116 '/compute/ext/extended_availability_zone/api/v2}'
117 'availability_zone')
118 vm_state = ('{http://docs.openstack.org'
119 '/compute/ext/extended_status/api/v1.1}vm_state')
120 task_state = ('{http://docs.openstack.org'
121 '/compute/ext/extended_status/api/v1.1}task_state')
Attila Fazekas3de4fe22014-03-20 17:21:16 +0100122 if 'tenantId' in json:
123 json['tenant_id'] = json.pop('tenantId')
124 if 'userId' in json:
125 json['user_id'] = json.pop('userId')
ivan-zhua5141d92013-03-06 23:12:43 +0800126 if diskConfig in json:
Attila Fazekasb3d707c2013-09-10 19:01:15 +0200127 json['OS-DCF:diskConfig'] = json.pop(diskConfig)
128 if terminated_at in json:
129 json['OS-SRV-USG:terminated_at'] = json.pop(terminated_at)
130 if launched_at in json:
131 json['OS-SRV-USG:launched_at'] = json.pop(launched_at)
132 if power_state in json:
133 json['OS-EXT-STS:power_state'] = json.pop(power_state)
134 if availability_zone in json:
135 json['OS-EXT-AZ:availability_zone'] = json.pop(availability_zone)
136 if vm_state in json:
137 json['OS-EXT-STS:vm_state'] = json.pop(vm_state)
138 if task_state in json:
139 json['OS-EXT-STS:task_state'] = json.pop(task_state)
Jaroslav Henner93f19e82012-12-12 20:24:17 +0100140 return json
141
142
vponomaryov960eeb42014-02-22 18:25:25 +0200143class ServersClientXML(rest_client.RestClient):
144 TYPE = "xml"
Dan Smithcf8fab62012-08-14 08:03:48 -0700145
Andrea Frittoli8bbdb162014-01-06 11:06:13 +0000146 def __init__(self, auth_provider):
147 super(ServersClientXML, self).__init__(auth_provider)
Matthew Treinish684d8992014-01-30 16:27:40 +0000148 self.service = CONF.compute.catalog_type
Dan Smithcf8fab62012-08-14 08:03:48 -0700149
150 def _parse_key_value(self, node):
Sean Daguef237ccb2013-01-04 15:19:14 -0500151 """Parse <foo key='key'>value</foo> data into {'key': 'value'}."""
Dan Smithcf8fab62012-08-14 08:03:48 -0700152 data = {}
153 for node in node.getchildren():
154 data[node.get('key')] = node.text
155 return data
156
157 def _parse_links(self, node, json):
158 del json['link']
159 json['links'] = []
160 for linknode in node.findall('{http://www.w3.org/2005/Atom}link'):
Matthew Treinish28f164c2014-03-04 18:55:06 +0000161 json['links'].append(xml_utils.xml_to_json(linknode))
Dan Smithcf8fab62012-08-14 08:03:48 -0700162
163 def _parse_server(self, body):
Jaroslav Henner93f19e82012-12-12 20:24:17 +0100164 json = _translate_server_xml_to_json(body)
165
Dan Smithcf8fab62012-08-14 08:03:48 -0700166 if 'metadata' in json and json['metadata']:
167 # NOTE(danms): if there was metadata, we need to re-parse
168 # that as a special type
Matthew Treinish28f164c2014-03-04 18:55:06 +0000169 metadata_tag = body.find('{%s}metadata' % xml_utils.XMLNS_11)
Dan Smithcf8fab62012-08-14 08:03:48 -0700170 json["metadata"] = self._parse_key_value(metadata_tag)
171 if 'link' in json:
172 self._parse_links(body, json)
173 for sub in ['image', 'flavor']:
174 if sub in json and 'link' in json[sub]:
175 self._parse_links(body, json[sub])
Dan Smithcf8fab62012-08-14 08:03:48 -0700176 return json
177
Rami Vaknin7b9f36b2013-02-20 00:09:07 +0200178 def _parse_xml_virtual_interfaces(self, xml_dom):
179 """
180 Return server's virtual interfaces XML as JSON.
181 """
182 data = {"virtual_interfaces": []}
183 for iface in xml_dom.getchildren():
184 data["virtual_interfaces"].append(
185 {"id": iface.get("id"),
186 "mac_address": iface.get("mac_address")})
187 return data
188
Dan Smithcf8fab62012-08-14 08:03:48 -0700189 def get_server(self, server_id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500190 """Returns the details of an existing server."""
vponomaryovf4c27f92014-02-18 10:56:42 +0200191 resp, body = self.get("servers/%s" % str(server_id))
Dan Smithcf8fab62012-08-14 08:03:48 -0700192 server = self._parse_server(etree.fromstring(body))
193 return resp, server
194
huangtianhua5232b662013-10-11 10:21:58 +0800195 def migrate_server(self, server_id, **kwargs):
196 """Migrates the given server ."""
197 return self.action(server_id, 'migrate', None, **kwargs)
198
Zhu Zhu9643e512013-09-23 09:13:07 -0500199 def lock_server(self, server_id, **kwargs):
200 """Locks the given server."""
201 return self.action(server_id, 'lock', None, **kwargs)
202
203 def unlock_server(self, server_id, **kwargs):
204 """Unlocks the given server."""
205 return self.action(server_id, 'unlock', None, **kwargs)
206
Prem Karat6631f802013-07-04 12:07:33 +0530207 def suspend_server(self, server_id, **kwargs):
208 """Suspends the provided server."""
209 return self.action(server_id, 'suspend', None, **kwargs)
210
211 def resume_server(self, server_id, **kwargs):
212 """Un-suspends the provided server."""
213 return self.action(server_id, 'resume', None, **kwargs)
214
215 def pause_server(self, server_id, **kwargs):
216 """Pauses the provided server."""
217 return self.action(server_id, 'pause', None, **kwargs)
218
219 def unpause_server(self, server_id, **kwargs):
220 """Un-pauses the provided server."""
221 return self.action(server_id, 'unpause', None, **kwargs)
222
Ken'ichi Ohmichi39437e22013-10-06 00:21:38 +0900223 def shelve_server(self, server_id, **kwargs):
224 """Shelves the provided server."""
225 return self.action(server_id, 'shelve', None, **kwargs)
226
227 def unshelve_server(self, server_id, **kwargs):
228 """Un-shelves the provided server."""
229 return self.action(server_id, 'unshelve', None, **kwargs)
230
Ken'ichi Ohmichi17b7f112014-02-20 06:33:49 +0900231 def shelve_offload_server(self, server_id, **kwargs):
232 """Shelve-offload the provided server."""
233 return self.action(server_id, 'shelveOffload', None, **kwargs)
234
LingxianKongc26e6072013-09-28 21:16:52 +0800235 def reset_state(self, server_id, state='error'):
236 """Resets the state of a server to active/error."""
237 return self.action(server_id, 'os-resetState', None, state=state)
238
Dan Smithcf8fab62012-08-14 08:03:48 -0700239 def delete_server(self, server_id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500240 """Deletes the given server."""
Dan Smithcf8fab62012-08-14 08:03:48 -0700241 return self.delete("servers/%s" % str(server_id))
242
243 def _parse_array(self, node):
244 array = []
245 for child in node.getchildren():
Matthew Treinish28f164c2014-03-04 18:55:06 +0000246 array.append(xml_utils.xml_to_json(child))
Dan Smithcf8fab62012-08-14 08:03:48 -0700247 return array
248
Attila Fazekas3de4fe22014-03-20 17:21:16 +0100249 def _parse_server_array(self, node):
250 array = []
251 for child in node.getchildren():
252 array.append(self._parse_server(child))
253 return array
254
Dan Smithcf8fab62012-08-14 08:03:48 -0700255 def list_servers(self, params=None):
ivan-zhu58f9ba32013-03-13 16:52:41 +0800256 url = 'servers'
Matthew Treinish26dd0fa2012-12-04 17:14:37 -0500257 if params:
258 url += '?%s' % urllib.urlencode(params)
Dan Smithcf8fab62012-08-14 08:03:48 -0700259
vponomaryovf4c27f92014-02-18 10:56:42 +0200260 resp, body = self.get(url)
Attila Fazekas3de4fe22014-03-20 17:21:16 +0100261 servers = self._parse_server_array(etree.fromstring(body))
Dan Smithcf8fab62012-08-14 08:03:48 -0700262 return resp, {"servers": servers}
263
264 def list_servers_with_detail(self, params=None):
265 url = 'servers/detail'
Matthew Treinish26dd0fa2012-12-04 17:14:37 -0500266 if params:
267 url += '?%s' % urllib.urlencode(params)
Dan Smithcf8fab62012-08-14 08:03:48 -0700268
vponomaryovf4c27f92014-02-18 10:56:42 +0200269 resp, body = self.get(url)
Attila Fazekas3de4fe22014-03-20 17:21:16 +0100270 servers = self._parse_server_array(etree.fromstring(body))
Dan Smithcf8fab62012-08-14 08:03:48 -0700271 return resp, {"servers": servers}
272
273 def update_server(self, server_id, name=None, meta=None, accessIPv4=None,
ivan-zhu72d7d5b2013-10-16 17:30:58 +0800274 accessIPv6=None, disk_config=None):
Matthew Treinish28f164c2014-03-04 18:55:06 +0000275 doc = xml_utils.Document()
276 server = xml_utils.Element("server")
Dan Smithcf8fab62012-08-14 08:03:48 -0700277 doc.append(server)
278
Sean Daguee623f752013-02-27 14:52:15 -0500279 if name is not None:
Dan Smithcf8fab62012-08-14 08:03:48 -0700280 server.add_attr("name", name)
Sean Daguee623f752013-02-27 14:52:15 -0500281 if accessIPv4 is not None:
Dan Smithcf8fab62012-08-14 08:03:48 -0700282 server.add_attr("accessIPv4", accessIPv4)
Sean Daguee623f752013-02-27 14:52:15 -0500283 if accessIPv6 is not None:
Dan Smithcf8fab62012-08-14 08:03:48 -0700284 server.add_attr("accessIPv6", accessIPv6)
ivan-zhu72d7d5b2013-10-16 17:30:58 +0800285 if disk_config is not None:
286 server.add_attr('xmlns:OS-DCF', "http://docs.openstack.org/"
287 "compute/ext/disk_config/api/v1.1")
288 server.add_attr("OS-DCF:diskConfig", disk_config)
Sean Daguee623f752013-02-27 14:52:15 -0500289 if meta is not None:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000290 metadata = xml_utils.Element("metadata")
Dan Smithcf8fab62012-08-14 08:03:48 -0700291 server.append(metadata)
292 for k, v in meta:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000293 meta = xml_utils.Element("meta", key=k)
294 meta.append(xml_utils.Text(v))
Dan Smithcf8fab62012-08-14 08:03:48 -0700295 metadata.append(meta)
296
vponomaryovf4c27f92014-02-18 10:56:42 +0200297 resp, body = self.put('servers/%s' % str(server_id), str(doc))
Matthew Treinish28f164c2014-03-04 18:55:06 +0000298 return resp, xml_utils.xml_to_json(etree.fromstring(body))
Dan Smithcf8fab62012-08-14 08:03:48 -0700299
300 def create_server(self, name, image_ref, flavor_ref, **kwargs):
301 """
302 Creates an instance of a server.
303 name (Required): The name of the server.
304 image_ref (Required): Reference to the image used to build the server.
305 flavor_ref (Required): The flavor used to build the server.
306 Following optional keyword arguments are accepted:
307 adminPass: Sets the initial root password.
308 key_name: Key name of keypair that was created earlier.
309 meta: A dictionary of values to be used as metadata.
310 personality: A list of dictionaries for files to be injected into
311 the server.
312 security_groups: A list of security group dicts.
313 networks: A list of network dicts with UUID and fixed_ip.
314 user_data: User data for instance.
315 availability_zone: Availability zone in which to launch instance.
316 accessIPv4: The IPv4 access address for the server.
317 accessIPv6: The IPv6 access address for the server.
318 min_count: Count of minimum number of instances to launch.
319 max_count: Count of maximum number of instances to launch.
320 disk_config: Determines if user or admin controls disk configuration.
Andrey Pavlov2a2fc412014-06-09 11:02:53 +0400321 block_device_mapping: Block device mapping for the server.
Dan Smithcf8fab62012-08-14 08:03:48 -0700322 """
Matthew Treinish28f164c2014-03-04 18:55:06 +0000323 server = xml_utils.Element("server",
324 xmlns=xml_utils.XMLNS_11,
325 imageRef=image_ref,
326 flavorRef=flavor_ref,
327 name=name)
Dan Smithcf8fab62012-08-14 08:03:48 -0700328
Sean Daguee623f752013-02-27 14:52:15 -0500329 for attr in ["adminPass", "accessIPv4", "accessIPv6", "key_name",
Mauro S. M. Rodriguesc5da4f42013-03-04 23:57:10 -0500330 "user_data", "availability_zone", "min_count",
Andrey Pavlov2a2fc412014-06-09 11:02:53 +0400331 "max_count", "return_reservation_id",
332 "block_device_mapping"]:
Dan Smithcf8fab62012-08-14 08:03:48 -0700333 if attr in kwargs:
334 server.add_attr(attr, kwargs[attr])
335
ivan-zhua5141d92013-03-06 23:12:43 +0800336 if 'disk_config' in kwargs:
337 server.add_attr('xmlns:OS-DCF', "http://docs.openstack.org/"
338 "compute/ext/disk_config/api/v1.1")
339 server.add_attr('OS-DCF:diskConfig', kwargs['disk_config'])
340
Sean Daguee623f752013-02-27 14:52:15 -0500341 if 'security_groups' in kwargs:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000342 secgroups = xml_utils.Element("security_groups")
Sean Daguee623f752013-02-27 14:52:15 -0500343 server.append(secgroups)
344 for secgroup in kwargs['security_groups']:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000345 s = xml_utils.Element("security_group", name=secgroup['name'])
Sean Daguee623f752013-02-27 14:52:15 -0500346 secgroups.append(s)
347
348 if 'networks' in kwargs:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000349 networks = xml_utils.Element("networks")
Sean Daguee623f752013-02-27 14:52:15 -0500350 server.append(networks)
351 for network in kwargs['networks']:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000352 s = xml_utils.Element("network", uuid=network['uuid'],
353 fixed_ip=network['fixed_ip'])
Sean Daguee623f752013-02-27 14:52:15 -0500354 networks.append(s)
355
Dan Smithcf8fab62012-08-14 08:03:48 -0700356 if 'meta' in kwargs:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000357 metadata = xml_utils.Element("metadata")
Dan Smithcf8fab62012-08-14 08:03:48 -0700358 server.append(metadata)
359 for k, v in kwargs['meta'].items():
Matthew Treinish28f164c2014-03-04 18:55:06 +0000360 meta = xml_utils.Element("meta", key=k)
361 meta.append(xml_utils.Text(v))
Dan Smithcf8fab62012-08-14 08:03:48 -0700362 metadata.append(meta)
363
Matthew Treinish2dfc2822012-08-16 16:57:08 -0400364 if 'personality' in kwargs:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000365 personality = xml_utils.Element('personality')
Matthew Treinish2dfc2822012-08-16 16:57:08 -0400366 server.append(personality)
367 for k in kwargs['personality']:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000368 temp = xml_utils.Element('file', path=k['path'])
369 temp.append(xml_utils.Text(k['contents']))
Matthew Treinish2dfc2822012-08-16 16:57:08 -0400370 personality.append(temp)
Dan Smithcf8fab62012-08-14 08:03:48 -0700371
raiesmh08cbe21b02014-03-12 17:04:44 +0530372 if 'sched_hints' in kwargs:
373 sched_hints = kwargs.get('sched_hints')
Matthew Treinish28f164c2014-03-04 18:55:06 +0000374 hints = xml_utils.Element("os:scheduler_hints")
375 hints.add_attr('xmlns:os', xml_utils.XMLNS_11)
raiesmh08cbe21b02014-03-12 17:04:44 +0530376 for attr in sched_hints:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000377 p1 = xml_utils.Element(attr)
raiesmh08cbe21b02014-03-12 17:04:44 +0530378 p1.append(sched_hints[attr])
379 hints.append(p1)
380 server.append(hints)
Matthew Treinish28f164c2014-03-04 18:55:06 +0000381 resp, body = self.post('servers', str(xml_utils.Document(server)))
Dan Smithcf8fab62012-08-14 08:03:48 -0700382 server = self._parse_server(etree.fromstring(body))
383 return resp, server
384
Zhi Kun Liue5401762013-09-11 20:45:48 +0800385 def wait_for_server_status(self, server_id, status, extra_timeout=0,
386 raise_on_error=True):
Sean Daguef237ccb2013-01-04 15:19:14 -0500387 """Waits for a server to reach a given status."""
Ken'ichi Ohmichi39437e22013-10-06 00:21:38 +0900388 return waiters.wait_for_server_status(self, server_id, status,
Zhi Kun Liue5401762013-09-11 20:45:48 +0800389 extra_timeout=extra_timeout,
390 raise_on_error=raise_on_error)
Dan Smithcf8fab62012-08-14 08:03:48 -0700391
392 def wait_for_server_termination(self, server_id, ignore_error=False):
Sean Daguef237ccb2013-01-04 15:19:14 -0500393 """Waits for server to reach termination."""
Dan Smithcf8fab62012-08-14 08:03:48 -0700394 start_time = int(time.time())
395 while True:
396 try:
397 resp, body = self.get_server(server_id)
398 except exceptions.NotFound:
399 return
400
401 server_status = body['status']
402 if server_status == 'ERROR' and not ignore_error:
Masayuki Igawaa0e786a2014-01-27 15:25:06 +0900403 raise exceptions.BuildErrorException(server_id=server_id)
Dan Smithcf8fab62012-08-14 08:03:48 -0700404
405 if int(time.time()) - start_time >= self.build_timeout:
406 raise exceptions.TimeoutException
407
408 time.sleep(self.build_interval)
409
410 def _parse_network(self, node):
411 addrs = []
412 for child in node.getchildren():
413 addrs.append({'version': int(child.get('version')),
zhhuabjcc51ccd2013-08-20 09:50:47 +0800414 'addr': child.get('addr')})
Dan Smithcf8fab62012-08-14 08:03:48 -0700415 return {node.get('id'): addrs}
416
417 def list_addresses(self, server_id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500418 """Lists all addresses for a server."""
vponomaryovf4c27f92014-02-18 10:56:42 +0200419 resp, body = self.get("servers/%s/ips" % str(server_id))
Dan Smithcf8fab62012-08-14 08:03:48 -0700420
421 networks = {}
Matthew Treinishb53989b2013-03-04 16:54:12 -0500422 xml_list = etree.fromstring(body)
423 for child in xml_list.getchildren():
Dan Smithcf8fab62012-08-14 08:03:48 -0700424 network = self._parse_network(child)
425 networks.update(**network)
426
427 return resp, networks
428
429 def list_addresses_by_network(self, server_id, network_id):
Sean Daguef237ccb2013-01-04 15:19:14 -0500430 """Lists all addresses of a specific network type for a server."""
Zhongyue Luoe0884a32012-09-25 17:24:17 +0800431 resp, body = self.get("servers/%s/ips/%s" % (str(server_id),
vponomaryovf4c27f92014-02-18 10:56:42 +0200432 network_id))
Dan Smithcf8fab62012-08-14 08:03:48 -0700433 network = self._parse_network(etree.fromstring(body))
434
435 return resp, network
436
Attila Fazekasd4299282013-02-22 13:25:23 +0100437 def action(self, server_id, action_name, response_key, **kwargs):
438 if 'xmlns' not in kwargs:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000439 kwargs['xmlns'] = xml_utils.XMLNS_11
440 doc = xml_utils.Document((xml_utils.Element(action_name, **kwargs)))
vponomaryovf4c27f92014-02-18 10:56:42 +0200441 resp, body = self.post("servers/%s/action" % server_id, str(doc))
Attila Fazekasd4299282013-02-22 13:25:23 +0100442 if response_key is not None:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000443 body = xml_utils.xml_to_json(etree.fromstring(body))
Attila Fazekasd4299282013-02-22 13:25:23 +0100444 return resp, body
445
ivan-zhuccc89462013-10-31 16:53:12 +0800446 def create_backup(self, server_id, backup_type, rotation, name):
447 """Backup a server instance."""
448 return self.action(server_id, "createBackup", None,
449 backup_type=backup_type,
450 rotation=rotation,
451 name=name)
452
Dan Smithcf8fab62012-08-14 08:03:48 -0700453 def change_password(self, server_id, password):
Attila Fazekasd4299282013-02-22 13:25:23 +0100454 return self.action(server_id, "changePassword", None,
455 adminPass=password)
Dan Smithcf8fab62012-08-14 08:03:48 -0700456
ivan-zhu6de5b042013-10-24 17:21:48 +0800457 def get_password(self, server_id):
vponomaryovf4c27f92014-02-18 10:56:42 +0200458 resp, body = self.get("servers/%s/os-server-password" % str(server_id))
Matthew Treinish28f164c2014-03-04 18:55:06 +0000459 body = xml_utils.xml_to_json(etree.fromstring(body))
ivan-zhu6de5b042013-10-24 17:21:48 +0800460 return resp, body
461
462 def delete_password(self, server_id):
463 """
464 Removes the encrypted server password from the metadata server
465 Note that this does not actually change the instance server
466 password.
467 """
vponomaryovf4c27f92014-02-18 10:56:42 +0200468 return self.delete("servers/%s/os-server-password" % str(server_id))
ivan-zhu6de5b042013-10-24 17:21:48 +0800469
Dan Smithcf8fab62012-08-14 08:03:48 -0700470 def reboot(self, server_id, reboot_type):
Attila Fazekasd4299282013-02-22 13:25:23 +0100471 return self.action(server_id, "reboot", None, type=reboot_type)
Dan Smithcf8fab62012-08-14 08:03:48 -0700472
Attila Fazekasd4299282013-02-22 13:25:23 +0100473 def rebuild(self, server_id, image_ref, **kwargs):
474 kwargs['imageRef'] = image_ref
ivan-zhua5141d92013-03-06 23:12:43 +0800475 if 'disk_config' in kwargs:
476 kwargs['OS-DCF:diskConfig'] = kwargs['disk_config']
477 del kwargs['disk_config']
478 kwargs['xmlns:OS-DCF'] = "http://docs.openstack.org/"\
479 "compute/ext/disk_config/api/v1.1"
480 kwargs['xmlns:atom'] = "http://www.w3.org/2005/Atom"
Attila Fazekasd4299282013-02-22 13:25:23 +0100481 if 'xmlns' not in kwargs:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000482 kwargs['xmlns'] = xml_utils.XMLNS_11
Attila Fazekasd4299282013-02-22 13:25:23 +0100483
484 attrs = kwargs.copy()
485 if 'metadata' in attrs:
486 del attrs['metadata']
Matthew Treinish28f164c2014-03-04 18:55:06 +0000487 rebuild = xml_utils.Element("rebuild", **attrs)
Dan Smithcf8fab62012-08-14 08:03:48 -0700488
Attila Fazekasd4299282013-02-22 13:25:23 +0100489 if 'metadata' in kwargs:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000490 metadata = xml_utils.Element("metadata")
Dan Smithcf8fab62012-08-14 08:03:48 -0700491 rebuild.append(metadata)
Attila Fazekasd4299282013-02-22 13:25:23 +0100492 for k, v in kwargs['metadata'].items():
Matthew Treinish28f164c2014-03-04 18:55:06 +0000493 meta = xml_utils.Element("meta", key=k)
494 meta.append(xml_utils.Text(v))
Dan Smithcf8fab62012-08-14 08:03:48 -0700495 metadata.append(meta)
496
497 resp, body = self.post('servers/%s/action' % server_id,
Matthew Treinish28f164c2014-03-04 18:55:06 +0000498 str(xml_utils.Document(rebuild)))
Dan Smithcf8fab62012-08-14 08:03:48 -0700499 server = self._parse_server(etree.fromstring(body))
500 return resp, server
501
Attila Fazekasd4299282013-02-22 13:25:23 +0100502 def resize(self, server_id, flavor_ref, **kwargs):
503 if 'disk_config' in kwargs:
ivan-zhua5141d92013-03-06 23:12:43 +0800504 kwargs['OS-DCF:diskConfig'] = kwargs['disk_config']
505 del kwargs['disk_config']
506 kwargs['xmlns:OS-DCF'] = "http://docs.openstack.org/"\
507 "compute/ext/disk_config/api/v1.1"
508 kwargs['xmlns:atom'] = "http://www.w3.org/2005/Atom"
Attila Fazekasd4299282013-02-22 13:25:23 +0100509 kwargs['flavorRef'] = flavor_ref
510 return self.action(server_id, 'resize', None, **kwargs)
Dan Smithcf8fab62012-08-14 08:03:48 -0700511
Attila Fazekasd4299282013-02-22 13:25:23 +0100512 def confirm_resize(self, server_id, **kwargs):
513 return self.action(server_id, 'confirmResize', None, **kwargs)
Dan Smithcf8fab62012-08-14 08:03:48 -0700514
Attila Fazekasd4299282013-02-22 13:25:23 +0100515 def revert_resize(self, server_id, **kwargs):
516 return self.action(server_id, 'revertResize', None, **kwargs)
Dan Smithcf8fab62012-08-14 08:03:48 -0700517
Liu, Zhi Kun3fb36952013-07-18 00:05:05 +0800518 def stop(self, server_id, **kwargs):
519 return self.action(server_id, 'os-stop', None, **kwargs)
520
521 def start(self, server_id, **kwargs):
522 return self.action(server_id, 'os-start', None, **kwargs)
523
Attila Fazekasd4299282013-02-22 13:25:23 +0100524 def create_image(self, server_id, name):
525 return self.action(server_id, 'createImage', None, name=name)
Dan Smithcf8fab62012-08-14 08:03:48 -0700526
Attila Fazekasd4299282013-02-22 13:25:23 +0100527 def add_security_group(self, server_id, name):
528 return self.action(server_id, 'addSecurityGroup', None, name=name)
Dan Smithcf8fab62012-08-14 08:03:48 -0700529
Attila Fazekasd4299282013-02-22 13:25:23 +0100530 def remove_security_group(self, server_id, name):
531 return self.action(server_id, 'removeSecurityGroup', None, name=name)
Attila Fazekase4cb04c2013-01-29 09:51:58 +0100532
ravikumar-venkatesan753262b2013-03-21 12:43:57 +0000533 def live_migrate_server(self, server_id, dest_host, use_block_migration):
534 """This should be called with administrator privileges ."""
535
Matthew Treinish28f164c2014-03-04 18:55:06 +0000536 req_body = xml_utils.Element("os-migrateLive",
537 xmlns=xml_utils.XMLNS_11,
538 disk_over_commit=False,
539 block_migration=use_block_migration,
540 host=dest_host)
ravikumar-venkatesan753262b2013-03-21 12:43:57 +0000541
542 resp, body = self.post("servers/%s/action" % str(server_id),
Matthew Treinish28f164c2014-03-04 18:55:06 +0000543 str(xml_utils.Document(req_body)))
ravikumar-venkatesan753262b2013-03-21 12:43:57 +0000544 return resp, body
545
meera-belurfd279d62013-02-15 15:35:46 -0800546 def list_server_metadata(self, server_id):
vponomaryovf4c27f92014-02-18 10:56:42 +0200547 resp, body = self.get("servers/%s/metadata" % str(server_id))
meera-belurfd279d62013-02-15 15:35:46 -0800548 body = self._parse_key_value(etree.fromstring(body))
549 return resp, body
550
Chris Yeohd0b52e72013-09-17 22:38:59 +0930551 def set_server_metadata(self, server_id, meta, no_metadata_field=False):
Matthew Treinish28f164c2014-03-04 18:55:06 +0000552 doc = xml_utils.Document()
Chris Yeohd0b52e72013-09-17 22:38:59 +0930553 if not no_metadata_field:
Matthew Treinish28f164c2014-03-04 18:55:06 +0000554 metadata = xml_utils.Element("metadata")
Chris Yeohd0b52e72013-09-17 22:38:59 +0930555 doc.append(metadata)
556 for k, v in meta.items():
Matthew Treinish28f164c2014-03-04 18:55:06 +0000557 meta_element = xml_utils.Element("meta", key=k)
558 meta_element.append(xml_utils.Text(v))
Chris Yeohd0b52e72013-09-17 22:38:59 +0930559 metadata.append(meta_element)
vponomaryovf4c27f92014-02-18 10:56:42 +0200560 resp, body = self.put('servers/%s/metadata' % str(server_id), str(doc))
Matthew Treinish28f164c2014-03-04 18:55:06 +0000561 return resp, xml_utils.xml_to_json(etree.fromstring(body))
meera-belurfd279d62013-02-15 15:35:46 -0800562
563 def update_server_metadata(self, server_id, meta):
Matthew Treinish28f164c2014-03-04 18:55:06 +0000564 doc = xml_utils.Document()
565 metadata = xml_utils.Element("metadata")
meera-belurfd279d62013-02-15 15:35:46 -0800566 doc.append(metadata)
567 for k, v in meta.items():
Matthew Treinish28f164c2014-03-04 18:55:06 +0000568 meta_element = xml_utils.Element("meta", key=k)
569 meta_element.append(xml_utils.Text(v))
meera-belurfd279d62013-02-15 15:35:46 -0800570 metadata.append(meta_element)
571 resp, body = self.post("/servers/%s/metadata" % str(server_id),
vponomaryovf4c27f92014-02-18 10:56:42 +0200572 str(doc))
Matthew Treinish28f164c2014-03-04 18:55:06 +0000573 body = xml_utils.xml_to_json(etree.fromstring(body))
meera-belurfd279d62013-02-15 15:35:46 -0800574 return resp, body
575
576 def get_server_metadata_item(self, server_id, key):
vponomaryovf4c27f92014-02-18 10:56:42 +0200577 resp, body = self.get("servers/%s/metadata/%s" % (str(server_id), key))
meera-belurfd279d62013-02-15 15:35:46 -0800578 return resp, dict([(etree.fromstring(body).attrib['key'],
Matthew Treinish28f164c2014-03-04 18:55:06 +0000579 xml_utils.xml_to_json(etree.fromstring(body)))])
meera-belurfd279d62013-02-15 15:35:46 -0800580
581 def set_server_metadata_item(self, server_id, key, meta):
Matthew Treinish28f164c2014-03-04 18:55:06 +0000582 doc = xml_utils.Document()
meera-belurfd279d62013-02-15 15:35:46 -0800583 for k, v in meta.items():
Matthew Treinish28f164c2014-03-04 18:55:06 +0000584 meta_element = xml_utils.Element("meta", key=k)
585 meta_element.append(xml_utils.Text(v))
meera-belurfd279d62013-02-15 15:35:46 -0800586 doc.append(meta_element)
587 resp, body = self.put('servers/%s/metadata/%s' % (str(server_id), key),
vponomaryovf4c27f92014-02-18 10:56:42 +0200588 str(doc))
Matthew Treinish28f164c2014-03-04 18:55:06 +0000589 return resp, xml_utils.xml_to_json(etree.fromstring(body))
meera-belurfd279d62013-02-15 15:35:46 -0800590
591 def delete_server_metadata_item(self, server_id, key):
592 resp, body = self.delete("servers/%s/metadata/%s" %
593 (str(server_id), key))
594 return resp, body
595
Attila Fazekase4cb04c2013-01-29 09:51:58 +0100596 def get_console_output(self, server_id, length):
Attila Fazekasd4299282013-02-22 13:25:23 +0100597 return self.action(server_id, 'os-getConsoleOutput', 'output',
598 length=length)
Rami Vaknin76bc8bd2013-02-17 16:18:27 +0200599
600 def list_virtual_interfaces(self, server_id):
601 """
602 List the virtual interfaces used in an instance.
603 """
604 resp, body = self.get('/'.join(['servers', server_id,
vponomaryovf4c27f92014-02-18 10:56:42 +0200605 'os-virtual-interfaces']))
Rami Vaknin7b9f36b2013-02-20 00:09:07 +0200606 virt_int = self._parse_xml_virtual_interfaces(etree.fromstring(body))
607 return resp, virt_int
nithya-ganesane6a36c82013-02-15 14:38:27 +0000608
Yuiko Takada7835d502014-01-15 10:15:03 +0000609 def rescue_server(self, server_id, **kwargs):
nithya-ganesane6a36c82013-02-15 14:38:27 +0000610 """Rescue the provided server."""
Yuiko Takada7835d502014-01-15 10:15:03 +0000611 return self.action(server_id, 'rescue', None, **kwargs)
nithya-ganesane6a36c82013-02-15 14:38:27 +0000612
613 def unrescue_server(self, server_id):
614 """Unrescue the provided server."""
615 return self.action(server_id, 'unrescue', None)
616
617 def attach_volume(self, server_id, volume_id, device='/dev/vdz'):
Matthew Treinish28f164c2014-03-04 18:55:06 +0000618 post_body = xml_utils.Element("volumeAttachment", volumeId=volume_id,
619 device=device)
nithya-ganesane6a36c82013-02-15 14:38:27 +0000620 resp, body = self.post('servers/%s/os-volume_attachments' % server_id,
Matthew Treinish28f164c2014-03-04 18:55:06 +0000621 str(xml_utils.Document(post_body)))
nithya-ganesane6a36c82013-02-15 14:38:27 +0000622 return resp, body
623
624 def detach_volume(self, server_id, volume_id):
625 headers = {'Content-Type': 'application/xml',
626 'Accept': 'application/xml'}
627 resp, body = self.delete('servers/%s/os-volume_attachments/%s' %
628 (server_id, volume_id), headers)
629 return resp, body
Leo Toyodafaca6ff2013-04-22 16:52:53 +0900630
Zhu Zhuda070852013-09-25 08:07:57 -0500631 def get_server_diagnostics(self, server_id):
632 """Get the usage data for a server."""
vponomaryovf4c27f92014-02-18 10:56:42 +0200633 resp, body = self.get("servers/%s/diagnostics" % server_id)
Matthew Treinish28f164c2014-03-04 18:55:06 +0000634 body = xml_utils.xml_to_json(etree.fromstring(body))
Zhu Zhuda070852013-09-25 08:07:57 -0500635 return resp, body
636
Leo Toyodafaca6ff2013-04-22 16:52:53 +0900637 def list_instance_actions(self, server_id):
638 """List the provided server action."""
vponomaryovf4c27f92014-02-18 10:56:42 +0200639 resp, body = self.get("servers/%s/os-instance-actions" % server_id)
Leo Toyodafaca6ff2013-04-22 16:52:53 +0900640 body = self._parse_array(etree.fromstring(body))
641 return resp, body
642
643 def get_instance_action(self, server_id, request_id):
644 """Returns the action details of the provided server."""
645 resp, body = self.get("servers/%s/os-instance-actions/%s" %
vponomaryovf4c27f92014-02-18 10:56:42 +0200646 (server_id, request_id))
Matthew Treinish28f164c2014-03-04 18:55:06 +0000647 body = xml_utils.xml_to_json(etree.fromstring(body))
Leo Toyodafaca6ff2013-04-22 16:52:53 +0900648 return resp, body
Lingxian Kongaecc1092013-10-03 16:18:46 +0800649
650 def force_delete_server(self, server_id, **kwargs):
651 """Force delete a server."""
652 return self.action(server_id, 'forceDelete', None, **kwargs)
653
654 def restore_soft_deleted_server(self, server_id, **kwargs):
655 """Restore a soft-deleted server."""
656 return self.action(server_id, 'restore', None, **kwargs)
Ghanshyam Mann79f4a092014-02-27 21:01:31 +0900657
658 def reset_network(self, server_id, **kwargs):
659 """Resets the Network of a server"""
660 return self.action(server_id, 'resetNetwork', None, **kwargs)
661
662 def inject_network_info(self, server_id, **kwargs):
663 """Inject the Network Info into server"""
664 return self.action(server_id, 'injectNetworkInfo', None, **kwargs)
Ghanshyam86d1a572014-03-05 10:19:25 +0900665
666 def get_vnc_console(self, server_id, console_type):
667 """Get URL of VNC console."""
668 return self.action(server_id, "os-getVNCConsole",
669 "console", type=console_type)