blob: 9587ffe50bd36082acd12ef8c89cf73cd9b6dd9f [file] [log] [blame]
Joseph Lanouxb3e1f872015-01-30 11:13:07 +00001# Copyright (c) 2015 Hewlett-Packard Development Company, L.P.
2# All Rights Reserved.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain 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,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
Clark Boylan844180e2017-03-15 15:24:58 -070016import base64
Markus Zoellerae36ce82017-03-20 16:27:26 +010017import socket
18import struct
Clark Boylan844180e2017-03-15 15:24:58 -070019import textwrap
20
Markus Zoellerae36ce82017-03-20 16:27:26 +010021import six
22from six.moves.urllib import parse as urlparse
23
Joseph Lanouxb3e1f872015-01-30 11:13:07 +000024from oslo_log import log as logging
25from oslo_utils import excutils
Joseph Lanouxb3e1f872015-01-30 11:13:07 +000026
27from tempest.common import fixed_network
Ken'ichi Ohmichi0eb153c2015-07-13 02:18:25 +000028from tempest.common import waiters
Joseph Lanouxb3e1f872015-01-30 11:13:07 +000029from tempest import config
Ken'ichi Ohmichi54030522016-03-02 11:01:34 -080030from tempest.lib.common import rest_client
Ken'ichi Ohmichi757833a2017-03-10 10:30:30 -080031from tempest.lib.common.utils import data_utils
Joseph Lanouxb3e1f872015-01-30 11:13:07 +000032
Markus Zoellerae36ce82017-03-20 16:27:26 +010033if six.PY2:
34 ord_func = ord
35else:
36 ord_func = int
37
Joseph Lanouxb3e1f872015-01-30 11:13:07 +000038CONF = config.CONF
39
40LOG = logging.getLogger(__name__)
41
42
Andrea Frittoli (andreaf)476e9192015-08-14 23:59:58 +010043def create_test_server(clients, validatable=False, validation_resources=None,
Joe Gordon8843f0f2015-03-17 15:07:34 -070044 tenant_network=None, wait_until=None,
Anusha Ramineni9aaef8b2016-01-19 10:56:40 +053045 volume_backed=False, name=None, flavor=None,
ghanshyam61db96e2016-12-16 12:49:25 +090046 image_id=None, **kwargs):
Joseph Lanouxb3e1f872015-01-30 11:13:07 +000047 """Common wrapper utility returning a test server.
48
49 This method is a common wrapper returning a test server that can be
50 pingable or sshable.
51
Takashi NATSUME6d5a2b42015-09-08 11:27:49 +090052 :param clients: Client manager which provides OpenStack Tempest clients.
Joseph Lanouxb3e1f872015-01-30 11:13:07 +000053 :param validatable: Whether the server will be pingable or sshable.
54 :param validation_resources: Resources created for the connection to the
Andrea Frittoli (andreaf)9df3a522016-07-06 14:09:48 +010055 server. Include a keypair, a security group and an IP.
Ken'ichi Ohmichid5bc31a2015-09-02 01:45:28 +000056 :param tenant_network: Tenant network to be used for creating a server.
Ken'ichi Ohmichifc25e692015-09-02 01:48:06 +000057 :param wait_until: Server status to wait for the server to reach after
Andrea Frittoli (andreaf)9df3a522016-07-06 14:09:48 +010058 its creation.
ghanshyam61db96e2016-12-16 12:49:25 +090059 :param volume_backed: Whether the server is volume backed or not.
60 If this is true, a volume will be created and
61 create server will be requested with
62 'block_device_mapping_v2' populated with below
63 values:
64 --------------------------------------------
65 bd_map_v2 = [{
66 'uuid': volume['volume']['id'],
67 'source_type': 'volume',
68 'destination_type': 'volume',
69 'boot_index': 0,
70 'delete_on_termination': True}]
71 kwargs['block_device_mapping_v2'] = bd_map_v2
72 ---------------------------------------------
73 If server needs to be booted from volume with other
74 combination of bdm inputs than mentioned above, then
75 pass the bdm inputs explicitly as kwargs and image_id
76 as empty string ('').
Andrea Frittoli (andreaf)9df3a522016-07-06 14:09:48 +010077 :param name: Name of the server to be provisioned. If not defined a random
78 string ending with '-instance' will be generated.
79 :param flavor: Flavor of the server to be provisioned. If not defined,
80 CONF.compute.flavor_ref will be used instead.
81 :param image_id: ID of the image to be used to provision the server. If not
82 defined, CONF.compute.image_ref will be used instead.
lei zhangdd552b22015-11-25 20:41:48 +080083 :returns: a tuple
Joseph Lanouxb3e1f872015-01-30 11:13:07 +000084 """
85
86 # TODO(jlanoux) add support of wait_until PINGABLE/SSHABLE
87
Anusha Ramineni9aaef8b2016-01-19 10:56:40 +053088 if name is None:
89 name = data_utils.rand_name(__name__ + "-instance")
90 if flavor is None:
91 flavor = CONF.compute.flavor_ref
92 if image_id is None:
93 image_id = CONF.compute.image_ref
Joseph Lanouxb3e1f872015-01-30 11:13:07 +000094
95 kwargs = fixed_network.set_networks_kwarg(
96 tenant_network, kwargs) or {}
97
Ghanshyam4de44ae2015-12-25 10:34:00 +090098 multiple_create_request = (max(kwargs.get('min_count', 0),
99 kwargs.get('max_count', 0)) > 1)
100
Joseph Lanouxb3e1f872015-01-30 11:13:07 +0000101 if CONF.validation.run_validation and validatable:
102 # As a first implementation, multiple pingable or sshable servers will
103 # not be supported
Ghanshyam4de44ae2015-12-25 10:34:00 +0900104 if multiple_create_request:
Joseph Lanouxb3e1f872015-01-30 11:13:07 +0000105 msg = ("Multiple pingable or sshable servers not supported at "
106 "this stage.")
107 raise ValueError(msg)
108
109 if 'security_groups' in kwargs:
110 kwargs['security_groups'].append(
111 {'name': validation_resources['security_group']['name']})
112 else:
113 try:
114 kwargs['security_groups'] = [
115 {'name': validation_resources['security_group']['name']}]
116 except KeyError:
117 LOG.debug("No security group provided.")
118
119 if 'key_name' not in kwargs:
120 try:
121 kwargs['key_name'] = validation_resources['keypair']['name']
122 except KeyError:
123 LOG.debug("No key provided.")
124
125 if CONF.validation.connect_method == 'floating':
Ken'ichi Ohmichifc25e692015-09-02 01:48:06 +0000126 if wait_until is None:
127 wait_until = 'ACTIVE'
Joseph Lanouxb3e1f872015-01-30 11:13:07 +0000128
Clark Boylan844180e2017-03-15 15:24:58 -0700129 if 'user_data' not in kwargs:
130 # If nothing overrides the default user data script then run
131 # a simple script on the host to print networking info. This is
132 # to aid in debugging ssh failures.
133 script = '''
134 #!/bin/sh
135 echo "Printing {user} user authorized keys"
136 cat ~{user}/.ssh/authorized_keys || true
137 '''.format(user=CONF.validation.image_ssh_user)
138 script_clean = textwrap.dedent(script).lstrip().encode('utf8')
139 script_b64 = base64.b64encode(script_clean)
140 kwargs['user_data'] = script_b64
141
Joe Gordon8843f0f2015-03-17 15:07:34 -0700142 if volume_backed:
zhuflc6ce5392016-08-17 14:34:37 +0800143 volume_name = data_utils.rand_name(__name__ + '-volume')
John Griffithbc678ad2015-09-29 09:38:39 -0600144 volumes_client = clients.volumes_v2_client
ghanshyam3bd0d2b2017-03-23 01:57:28 +0000145 params = {'name': volume_name,
ghanshyam61db96e2016-12-16 12:49:25 +0900146 'imageRef': image_id,
147 'size': CONF.volume.volume_size}
148 volume = volumes_client.create_volume(**params)
lkuchlan52d7b0d2016-11-07 20:53:19 +0200149 waiters.wait_for_volume_resource_status(volumes_client,
150 volume['volume']['id'],
151 'available')
Joe Gordon8843f0f2015-03-17 15:07:34 -0700152
153 bd_map_v2 = [{
154 'uuid': volume['volume']['id'],
155 'source_type': 'volume',
156 'destination_type': 'volume',
157 'boot_index': 0,
ghanshyam61db96e2016-12-16 12:49:25 +0900158 'delete_on_termination': True}]
Joe Gordon8843f0f2015-03-17 15:07:34 -0700159 kwargs['block_device_mapping_v2'] = bd_map_v2
160
161 # Since this is boot from volume an image does not need
162 # to be specified.
163 image_id = ''
164
Ken'ichi Ohmichif2d436e2015-09-03 01:13:16 +0000165 body = clients.servers_client.create_server(name=name, imageRef=image_id,
166 flavorRef=flavor,
Joseph Lanouxb3e1f872015-01-30 11:13:07 +0000167 **kwargs)
168
169 # handle the case of multiple servers
Ghanshyam4de44ae2015-12-25 10:34:00 +0900170 if multiple_create_request:
Joseph Lanouxb3e1f872015-01-30 11:13:07 +0000171 # Get servers created which name match with name param.
172 body_servers = clients.servers_client.list_servers()
173 servers = \
174 [s for s in body_servers['servers'] if s['name'].startswith(name)]
ghanshyam0f825252015-08-25 16:02:50 +0900175 else:
Ken'ichi Ohmichi54030522016-03-02 11:01:34 -0800176 body = rest_client.ResponseBody(body.response, body['server'])
ghanshyam0f825252015-08-25 16:02:50 +0900177 servers = [body]
Joseph Lanouxb3e1f872015-01-30 11:13:07 +0000178
179 # The name of the method to associate a floating IP to as server is too
180 # long for PEP8 compliance so:
John Warrene74890a2015-11-11 15:18:01 -0500181 assoc = clients.compute_floating_ips_client.associate_floating_ip_to_server
Joseph Lanouxb3e1f872015-01-30 11:13:07 +0000182
Ken'ichi Ohmichifc25e692015-09-02 01:48:06 +0000183 if wait_until:
Joseph Lanouxb3e1f872015-01-30 11:13:07 +0000184 for server in servers:
185 try:
Ken'ichi Ohmichi0eb153c2015-07-13 02:18:25 +0000186 waiters.wait_for_server_status(
Ken'ichi Ohmichifc25e692015-09-02 01:48:06 +0000187 clients.servers_client, server['id'], wait_until)
Joseph Lanouxb3e1f872015-01-30 11:13:07 +0000188
189 # Multiple validatable servers are not supported for now. Their
190 # creation will fail with the condition above (l.58).
191 if CONF.validation.run_validation and validatable:
192 if CONF.validation.connect_method == 'floating':
193 assoc(floating_ip=validation_resources[
194 'floating_ip']['ip'],
195 server_id=servers[0]['id'])
196
197 except Exception:
198 with excutils.save_and_reraise_exception():
Jordan Pittier87ba2872016-03-08 11:43:11 +0100199 for server in servers:
200 try:
201 clients.servers_client.delete_server(
202 server['id'])
203 except Exception:
Jordan Pittier525ec712016-12-07 17:51:26 +0100204 LOG.exception('Deleting server %s failed',
205 server['id'])
Joseph Lanouxb3e1f872015-01-30 11:13:07 +0000206
207 return body, servers
ghanshyam017b5fe2016-04-15 18:49:26 +0900208
209
ghanshyam4c1391c2016-12-01 13:13:06 +0900210def shelve_server(servers_client, server_id, force_shelve_offload=False):
ghanshyam017b5fe2016-04-15 18:49:26 +0900211 """Common wrapper utility to shelve server.
212
213 This method is a common wrapper to make server in 'SHELVED'
214 or 'SHELVED_OFFLOADED' state.
215
ghanshyam4c1391c2016-12-01 13:13:06 +0900216 :param servers_clients: Compute servers client instance.
ghanshyam017b5fe2016-04-15 18:49:26 +0900217 :param server_id: Server to make in shelve state
218 :param force_shelve_offload: Forcefully offload shelve server if it
219 is configured not to offload server
220 automatically after offload time.
221 """
ghanshyam4c1391c2016-12-01 13:13:06 +0900222 servers_client.shelve_server(server_id)
ghanshyam017b5fe2016-04-15 18:49:26 +0900223
224 offload_time = CONF.compute.shelved_offload_time
225 if offload_time >= 0:
ghanshyam4c1391c2016-12-01 13:13:06 +0900226 waiters.wait_for_server_status(servers_client, server_id,
ghanshyam017b5fe2016-04-15 18:49:26 +0900227 'SHELVED_OFFLOADED',
228 extra_timeout=offload_time)
229 else:
ghanshyam4c1391c2016-12-01 13:13:06 +0900230 waiters.wait_for_server_status(servers_client, server_id, 'SHELVED')
ghanshyam017b5fe2016-04-15 18:49:26 +0900231 if force_shelve_offload:
ghanshyam4c1391c2016-12-01 13:13:06 +0900232 servers_client.shelve_offload_server(server_id)
233 waiters.wait_for_server_status(servers_client, server_id,
ghanshyam017b5fe2016-04-15 18:49:26 +0900234 'SHELVED_OFFLOADED')
Markus Zoellerae36ce82017-03-20 16:27:26 +0100235
236
237def create_websocket(url):
238 url = urlparse.urlparse(url)
239 client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
240 client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
241 client_socket.connect((url.hostname, url.port))
242 # Turn the Socket into a WebSocket to do the communication
243 return _WebSocket(client_socket, url)
244
245
246class _WebSocket(object):
247 def __init__(self, client_socket, url):
248 """Contructor for the WebSocket wrapper to the socket."""
249 self._socket = client_socket
250 # Upgrade the HTTP connection to a WebSocket
251 self._upgrade(url)
252
253 def receive_frame(self):
254 """Wrapper for receiving data to parse the WebSocket frame format"""
255 # We need to loop until we either get some bytes back in the frame
256 # or no data was received (meaning the socket was closed). This is
257 # done to handle the case where we get back some empty frames
258 while True:
259 header = self._socket.recv(2)
260 # If we didn't receive any data, just return None
Masayuki Igawa0c0f0142017-04-10 17:22:02 +0900261 if not header:
Markus Zoellerae36ce82017-03-20 16:27:26 +0100262 return None
263 # We will make the assumption that we are only dealing with
264 # frames less than 125 bytes here (for the negotiation) and
265 # that only the 2nd byte contains the length, and since the
266 # server doesn't do masking, we can just read the data length
267 if ord_func(header[1]) & 127 > 0:
268 return self._socket.recv(ord_func(header[1]) & 127)
269
270 def send_frame(self, data):
271 """Wrapper for sending data to add in the WebSocket frame format."""
272 frame_bytes = list()
273 # For the first byte, want to say we are sending binary data (130)
274 frame_bytes.append(130)
275 # Only sending negotiation data so don't need to worry about > 125
276 # We do need to add the bit that says we are masking the data
277 frame_bytes.append(len(data) | 128)
278 # We don't really care about providing a random mask for security
279 # So we will just hard-code a value since a test program
280 mask = [7, 2, 1, 9]
281 for i in range(len(mask)):
282 frame_bytes.append(mask[i])
283 # Mask each of the actual data bytes that we are going to send
284 for i in range(len(data)):
285 frame_bytes.append(ord_func(data[i]) ^ mask[i % 4])
286 # Convert our integer list to a binary array of bytes
287 frame_bytes = struct.pack('!%iB' % len(frame_bytes), * frame_bytes)
288 self._socket.sendall(frame_bytes)
289
290 def close(self):
291 """Helper method to close the connection."""
292 # Close down the real socket connection and exit the test program
293 if self._socket is not None:
294 self._socket.shutdown(1)
295 self._socket.close()
296 self._socket = None
297
298 def _upgrade(self, url):
299 """Upgrade the HTTP connection to a WebSocket and verify."""
300 # The real request goes to the /websockify URI always
301 reqdata = 'GET /websockify HTTP/1.1\r\n'
302 reqdata += 'Host: %s:%s\r\n' % (url.hostname, url.port)
303 # Tell the HTTP Server to Upgrade the connection to a WebSocket
304 reqdata += 'Upgrade: websocket\r\nConnection: Upgrade\r\n'
305 # The token=xxx is sent as a Cookie not in the URI
306 reqdata += 'Cookie: %s\r\n' % url.query
307 # Use a hard-coded WebSocket key since a test program
308 reqdata += 'Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==\r\n'
309 reqdata += 'Sec-WebSocket-Version: 13\r\n'
310 # We are choosing to use binary even though browser may do Base64
311 reqdata += 'Sec-WebSocket-Protocol: binary\r\n\r\n'
312 # Send the HTTP GET request and get the response back
313 self._socket.sendall(reqdata.encode('utf8'))
314 self.response = data = self._socket.recv(4096)
315 # Loop through & concatenate all of the data in the response body
Masayuki Igawa0c0f0142017-04-10 17:22:02 +0900316 while data and self.response.find(b'\r\n\r\n') < 0:
Markus Zoellerae36ce82017-03-20 16:27:26 +0100317 data = self._socket.recv(4096)
318 self.response += data