Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 1 | # 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 Boylan | 844180e | 2017-03-15 15:24:58 -0700 | [diff] [blame] | 16 | import base64 |
Markus Zoeller | ae36ce8 | 2017-03-20 16:27:26 +0100 | [diff] [blame] | 17 | import socket |
| 18 | import struct |
Clark Boylan | 844180e | 2017-03-15 15:24:58 -0700 | [diff] [blame] | 19 | import textwrap |
| 20 | |
Markus Zoeller | ae36ce8 | 2017-03-20 16:27:26 +0100 | [diff] [blame] | 21 | import six |
| 22 | from six.moves.urllib import parse as urlparse |
| 23 | |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 24 | from oslo_log import log as logging |
| 25 | from oslo_utils import excutils |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 26 | |
| 27 | from tempest.common import fixed_network |
Ken'ichi Ohmichi | 0eb153c | 2015-07-13 02:18:25 +0000 | [diff] [blame] | 28 | from tempest.common import waiters |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 29 | from tempest import config |
Ken'ichi Ohmichi | 5403052 | 2016-03-02 11:01:34 -0800 | [diff] [blame] | 30 | from tempest.lib.common import rest_client |
Ken'ichi Ohmichi | 757833a | 2017-03-10 10:30:30 -0800 | [diff] [blame] | 31 | from tempest.lib.common.utils import data_utils |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 32 | |
Markus Zoeller | ae36ce8 | 2017-03-20 16:27:26 +0100 | [diff] [blame] | 33 | if six.PY2: |
| 34 | ord_func = ord |
| 35 | else: |
| 36 | ord_func = int |
| 37 | |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 38 | CONF = config.CONF |
| 39 | |
| 40 | LOG = logging.getLogger(__name__) |
| 41 | |
| 42 | |
Andrea Frittoli (andreaf) | 476e919 | 2015-08-14 23:59:58 +0100 | [diff] [blame] | 43 | def create_test_server(clients, validatable=False, validation_resources=None, |
Joe Gordon | 8843f0f | 2015-03-17 15:07:34 -0700 | [diff] [blame] | 44 | tenant_network=None, wait_until=None, |
Anusha Ramineni | 9aaef8b | 2016-01-19 10:56:40 +0530 | [diff] [blame] | 45 | volume_backed=False, name=None, flavor=None, |
ghanshyam | 61db96e | 2016-12-16 12:49:25 +0900 | [diff] [blame] | 46 | image_id=None, **kwargs): |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 47 | """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 NATSUME | 6d5a2b4 | 2015-09-08 11:27:49 +0900 | [diff] [blame] | 52 | :param clients: Client manager which provides OpenStack Tempest clients. |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 53 | :param validatable: Whether the server will be pingable or sshable. |
| 54 | :param validation_resources: Resources created for the connection to the |
Andrea Frittoli (andreaf) | 9df3a52 | 2016-07-06 14:09:48 +0100 | [diff] [blame] | 55 | server. Include a keypair, a security group and an IP. |
Ken'ichi Ohmichi | d5bc31a | 2015-09-02 01:45:28 +0000 | [diff] [blame] | 56 | :param tenant_network: Tenant network to be used for creating a server. |
Ken'ichi Ohmichi | fc25e69 | 2015-09-02 01:48:06 +0000 | [diff] [blame] | 57 | :param wait_until: Server status to wait for the server to reach after |
Andrea Frittoli (andreaf) | 9df3a52 | 2016-07-06 14:09:48 +0100 | [diff] [blame] | 58 | its creation. |
ghanshyam | 61db96e | 2016-12-16 12:49:25 +0900 | [diff] [blame] | 59 | :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) | 9df3a52 | 2016-07-06 14:09:48 +0100 | [diff] [blame] | 77 | :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 zhang | dd552b2 | 2015-11-25 20:41:48 +0800 | [diff] [blame] | 83 | :returns: a tuple |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 84 | """ |
| 85 | |
| 86 | # TODO(jlanoux) add support of wait_until PINGABLE/SSHABLE |
| 87 | |
Anusha Ramineni | 9aaef8b | 2016-01-19 10:56:40 +0530 | [diff] [blame] | 88 | 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 Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 94 | |
| 95 | kwargs = fixed_network.set_networks_kwarg( |
| 96 | tenant_network, kwargs) or {} |
| 97 | |
Ghanshyam | 4de44ae | 2015-12-25 10:34:00 +0900 | [diff] [blame] | 98 | multiple_create_request = (max(kwargs.get('min_count', 0), |
| 99 | kwargs.get('max_count', 0)) > 1) |
| 100 | |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 101 | if CONF.validation.run_validation and validatable: |
| 102 | # As a first implementation, multiple pingable or sshable servers will |
| 103 | # not be supported |
Ghanshyam | 4de44ae | 2015-12-25 10:34:00 +0900 | [diff] [blame] | 104 | if multiple_create_request: |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 105 | 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 Ohmichi | fc25e69 | 2015-09-02 01:48:06 +0000 | [diff] [blame] | 126 | if wait_until is None: |
| 127 | wait_until = 'ACTIVE' |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 128 | |
Clark Boylan | 844180e | 2017-03-15 15:24:58 -0700 | [diff] [blame] | 129 | 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 Gordon | 8843f0f | 2015-03-17 15:07:34 -0700 | [diff] [blame] | 142 | if volume_backed: |
zhufl | c6ce539 | 2016-08-17 14:34:37 +0800 | [diff] [blame] | 143 | volume_name = data_utils.rand_name(__name__ + '-volume') |
John Griffith | bc678ad | 2015-09-29 09:38:39 -0600 | [diff] [blame] | 144 | volumes_client = clients.volumes_v2_client |
ghanshyam | 3bd0d2b | 2017-03-23 01:57:28 +0000 | [diff] [blame] | 145 | params = {'name': volume_name, |
ghanshyam | 61db96e | 2016-12-16 12:49:25 +0900 | [diff] [blame] | 146 | 'imageRef': image_id, |
| 147 | 'size': CONF.volume.volume_size} |
| 148 | volume = volumes_client.create_volume(**params) |
lkuchlan | 52d7b0d | 2016-11-07 20:53:19 +0200 | [diff] [blame] | 149 | waiters.wait_for_volume_resource_status(volumes_client, |
| 150 | volume['volume']['id'], |
| 151 | 'available') |
Joe Gordon | 8843f0f | 2015-03-17 15:07:34 -0700 | [diff] [blame] | 152 | |
| 153 | bd_map_v2 = [{ |
| 154 | 'uuid': volume['volume']['id'], |
| 155 | 'source_type': 'volume', |
| 156 | 'destination_type': 'volume', |
| 157 | 'boot_index': 0, |
ghanshyam | 61db96e | 2016-12-16 12:49:25 +0900 | [diff] [blame] | 158 | 'delete_on_termination': True}] |
Joe Gordon | 8843f0f | 2015-03-17 15:07:34 -0700 | [diff] [blame] | 159 | 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 Ohmichi | f2d436e | 2015-09-03 01:13:16 +0000 | [diff] [blame] | 165 | body = clients.servers_client.create_server(name=name, imageRef=image_id, |
| 166 | flavorRef=flavor, |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 167 | **kwargs) |
| 168 | |
| 169 | # handle the case of multiple servers |
Ghanshyam | 4de44ae | 2015-12-25 10:34:00 +0900 | [diff] [blame] | 170 | if multiple_create_request: |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 171 | # 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)] |
ghanshyam | 0f82525 | 2015-08-25 16:02:50 +0900 | [diff] [blame] | 175 | else: |
Ken'ichi Ohmichi | 5403052 | 2016-03-02 11:01:34 -0800 | [diff] [blame] | 176 | body = rest_client.ResponseBody(body.response, body['server']) |
ghanshyam | 0f82525 | 2015-08-25 16:02:50 +0900 | [diff] [blame] | 177 | servers = [body] |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 178 | |
| 179 | # The name of the method to associate a floating IP to as server is too |
| 180 | # long for PEP8 compliance so: |
John Warren | e74890a | 2015-11-11 15:18:01 -0500 | [diff] [blame] | 181 | assoc = clients.compute_floating_ips_client.associate_floating_ip_to_server |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 182 | |
Ken'ichi Ohmichi | fc25e69 | 2015-09-02 01:48:06 +0000 | [diff] [blame] | 183 | if wait_until: |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 184 | for server in servers: |
| 185 | try: |
Ken'ichi Ohmichi | 0eb153c | 2015-07-13 02:18:25 +0000 | [diff] [blame] | 186 | waiters.wait_for_server_status( |
Ken'ichi Ohmichi | fc25e69 | 2015-09-02 01:48:06 +0000 | [diff] [blame] | 187 | clients.servers_client, server['id'], wait_until) |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 188 | |
| 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 Pittier | 87ba287 | 2016-03-08 11:43:11 +0100 | [diff] [blame] | 199 | for server in servers: |
| 200 | try: |
| 201 | clients.servers_client.delete_server( |
| 202 | server['id']) |
| 203 | except Exception: |
Jordan Pittier | 525ec71 | 2016-12-07 17:51:26 +0100 | [diff] [blame] | 204 | LOG.exception('Deleting server %s failed', |
| 205 | server['id']) |
Joseph Lanoux | b3e1f87 | 2015-01-30 11:13:07 +0000 | [diff] [blame] | 206 | |
| 207 | return body, servers |
ghanshyam | 017b5fe | 2016-04-15 18:49:26 +0900 | [diff] [blame] | 208 | |
| 209 | |
ghanshyam | 4c1391c | 2016-12-01 13:13:06 +0900 | [diff] [blame] | 210 | def shelve_server(servers_client, server_id, force_shelve_offload=False): |
ghanshyam | 017b5fe | 2016-04-15 18:49:26 +0900 | [diff] [blame] | 211 | """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 | |
ghanshyam | 4c1391c | 2016-12-01 13:13:06 +0900 | [diff] [blame] | 216 | :param servers_clients: Compute servers client instance. |
ghanshyam | 017b5fe | 2016-04-15 18:49:26 +0900 | [diff] [blame] | 217 | :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 | """ |
ghanshyam | 4c1391c | 2016-12-01 13:13:06 +0900 | [diff] [blame] | 222 | servers_client.shelve_server(server_id) |
ghanshyam | 017b5fe | 2016-04-15 18:49:26 +0900 | [diff] [blame] | 223 | |
| 224 | offload_time = CONF.compute.shelved_offload_time |
| 225 | if offload_time >= 0: |
ghanshyam | 4c1391c | 2016-12-01 13:13:06 +0900 | [diff] [blame] | 226 | waiters.wait_for_server_status(servers_client, server_id, |
ghanshyam | 017b5fe | 2016-04-15 18:49:26 +0900 | [diff] [blame] | 227 | 'SHELVED_OFFLOADED', |
| 228 | extra_timeout=offload_time) |
| 229 | else: |
ghanshyam | 4c1391c | 2016-12-01 13:13:06 +0900 | [diff] [blame] | 230 | waiters.wait_for_server_status(servers_client, server_id, 'SHELVED') |
ghanshyam | 017b5fe | 2016-04-15 18:49:26 +0900 | [diff] [blame] | 231 | if force_shelve_offload: |
ghanshyam | 4c1391c | 2016-12-01 13:13:06 +0900 | [diff] [blame] | 232 | servers_client.shelve_offload_server(server_id) |
| 233 | waiters.wait_for_server_status(servers_client, server_id, |
ghanshyam | 017b5fe | 2016-04-15 18:49:26 +0900 | [diff] [blame] | 234 | 'SHELVED_OFFLOADED') |
Markus Zoeller | ae36ce8 | 2017-03-20 16:27:26 +0100 | [diff] [blame] | 235 | |
| 236 | |
| 237 | def 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 | |
| 246 | class _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 Igawa | 0c0f014 | 2017-04-10 17:22:02 +0900 | [diff] [blame] | 261 | if not header: |
Markus Zoeller | ae36ce8 | 2017-03-20 16:27:26 +0100 | [diff] [blame] | 262 | 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 Igawa | 0c0f014 | 2017-04-10 17:22:02 +0900 | [diff] [blame] | 316 | while data and self.response.find(b'\r\n\r\n') < 0: |
Markus Zoeller | ae36ce8 | 2017-03-20 16:27:26 +0100 | [diff] [blame] | 317 | data = self._socket.recv(4096) |
| 318 | self.response += data |