blob: 898e4b9004e5faa812ace8dc85387fe3575815b1 [file] [log] [blame]
Chandan Kumar5e619872017-09-07 22:23:55 +05301# Copyright 2011, VMware, Inc.
2# 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#
16# Borrowed from nova code base, more utilities will be added/borrowed as and
17# when needed.
18
19"""Utilities and helper functions."""
20
Chandan Kumar667d3d32017-09-22 12:24:06 +053021import threading
22import time
zheng.yong74e760a2019-05-22 14:16:14 +080023try:
24 import urlparse
25except ImportError:
26 from urllib import parse as urlparse
Chandan Kumar667d3d32017-09-22 12:24:06 +053027
Brian Haley33ef4602018-04-26 14:37:49 -040028import eventlet
Rodolfo Alonso Hernandez0adf8a22020-06-11 11:28:25 +000029
Maciej Józefczyk328edc82019-09-16 14:05:48 +000030from tempest.lib import exceptions
Brian Haley33ef4602018-04-26 14:37:49 -040031
Rodolfo Alonso Hernandez0adf8a22020-06-11 11:28:25 +000032
zheng.yong74e760a2019-05-22 14:16:14 +080033SCHEMA_PORT_MAPPING = {
34 "http": 80,
35 "https": 443,
36}
37
Chandan Kumar5e619872017-09-07 22:23:55 +053038
39class classproperty(object):
40 def __init__(self, f):
41 self.func = f
42
43 def __get__(self, obj, owner):
Chandan Kumar667d3d32017-09-22 12:24:06 +053044 return self.func(owner)
45
Chandan Kumar5e619872017-09-07 22:23:55 +053046
47class WaitTimeout(Exception):
48 """Default exception coming from wait_until_true() function."""
49
50
51class LockWithTimer(object):
52 def __init__(self, threshold):
53 self._threshold = threshold
54 self.timestamp = 0
55 self._lock = threading.Lock()
56
57 def acquire(self):
58 return self._lock.acquire(False)
59
60 def release(self):
61 return self._lock.release()
62
63 def time_to_wait(self):
64 return self.timestamp - time.time() + self._threshold
65
Chandan Kumar667d3d32017-09-22 12:24:06 +053066
Chandan Kumar5e619872017-09-07 22:23:55 +053067def wait_until_true(predicate, timeout=60, sleep=1, exception=None):
Brian Haleyae328b92018-10-09 19:51:54 -040068 """Wait until callable predicate is evaluated as True
69
Chandan Kumar5e619872017-09-07 22:23:55 +053070 :param predicate: Callable deciding whether waiting should continue.
71 Best practice is to instantiate predicate with functools.partial()
72 :param timeout: Timeout in seconds how long should function wait.
73 :param sleep: Polling interval for results in seconds.
74 :param exception: Exception instance to raise on timeout. If None is passed
75 (default) then WaitTimeout exception is raised.
76 """
77 try:
78 with eventlet.Timeout(timeout):
79 while not predicate():
80 eventlet.sleep(sleep)
81 except eventlet.Timeout:
82 if exception is not None:
Brian Haley8aaa73f2018-10-09 19:55:44 -040083 # pylint: disable=raising-bad-type
Chandan Kumar5e619872017-09-07 22:23:55 +053084 raise exception
85 raise WaitTimeout("Timed out after %d seconds" % timeout)
Brian Haleyba800452017-12-14 10:30:48 -050086
87
Federico Ressi0e04f8f2018-10-24 12:19:05 +020088def override_class(overriden_class, overrider_class):
89 """Override class definition with a MixIn class
90
91 If overriden_class is not a subclass of overrider_class then it creates
92 a new class that has as bases overrider_class and overriden_class.
93 """
94
95 if not issubclass(overriden_class, overrider_class):
96 name = overriden_class.__name__
97 bases = (overrider_class, overriden_class)
98 overriden_class = type(name, bases, {})
99 return overriden_class
zheng.yong74e760a2019-05-22 14:16:14 +0800100
101
102def normalize_url(url):
103 """Normalize url without port with schema default port
104
105 """
106 parse_result = urlparse.urlparse(url)
107 (scheme, netloc, url, params, query, fragment) = parse_result
108 port = parse_result.port
109 if scheme in SCHEMA_PORT_MAPPING and not port:
110 netloc = netloc + ":" + str(SCHEMA_PORT_MAPPING[scheme])
111 return urlparse.urlunparse((scheme, netloc, url, params, query, fragment))
Maciej Józefczyk328edc82019-09-16 14:05:48 +0000112
113
114def kill_nc_process(ssh_client):
115 cmd = "killall -q nc"
116 try:
117 ssh_client.exec_command(cmd)
118 except exceptions.SSHExecCommandFailed:
119 pass
120
121
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +0100122def process_is_running(ssh_client, process_name):
123 try:
124 ssh_client.exec_command("pidof %s" % process_name)
125 return True
126 except exceptions.SSHExecCommandFailed:
127 return False
128
129
Maciej Józefczyk328edc82019-09-16 14:05:48 +0000130def spawn_http_server(ssh_client, port, message):
131 cmd = ("(echo -e 'HTTP/1.1 200 OK\r\n'; echo '%(msg)s') "
132 "| sudo nc -lp %(port)d &" % {'msg': message, 'port': port})
133 ssh_client.exec_command(cmd)
134
135
136def call_url_remote(ssh_client, url):
137 cmd = "curl %s --retry 3 --connect-timeout 2" % url
138 return ssh_client.exec_command(cmd)
Alex Katzbd2bfd42021-05-26 18:12:36 +0300139
140
141class StatefulConnection:
142 """Class to test connection that should remain opened
143
144 Can be used to perform some actions while the initiated connection
145 remain opened
146 """
147
148 def __init__(self, client_ssh, server_ssh, target_ip, target_port):
149 self.client_ssh = client_ssh
150 self.server_ssh = server_ssh
151 self.ip = target_ip
152 self.port = target_port
153 self.connection_started = False
154 self.test_attempt = 0
155
156 def __enter__(self):
157 return self
158
159 @property
160 def test_str(self):
161 return 'attempt_{}'.format(str(self.test_attempt).zfill(3))
162
163 def _start_connection(self):
164 self.server_ssh.exec_command(
165 'echo "{}" > input.txt'.format(self.test_str))
166 self.server_ssh.exec_command('tail -f input.txt | nc -lp '
167 '{} &> output.txt &'.format(self.port))
168 self.client_ssh.exec_command(
169 'echo "{}" > input.txt'.format(self.test_str))
170 self.client_ssh.exec_command('tail -f input.txt | nc {} {} &>'
171 'output.txt &'.format(self.ip, self.port))
172
173 def _test_connection(self):
174 if not self.connection_started:
175 self._start_connection()
176 else:
177 self.server_ssh.exec_command(
178 'echo "{}" >> input.txt'.format(self.test_str))
179 self.client_ssh.exec_command(
180 'echo "{}" >> input.txt & sleep 1'.format(self.test_str))
181 try:
182 self.server_ssh.exec_command(
183 'grep {} output.txt'.format(self.test_str))
184 self.client_ssh.exec_command(
185 'grep {} output.txt'.format(self.test_str))
186 if not self.should_pass:
187 return False
188 else:
189 if not self.connection_started:
190 self.connection_started = True
191 return True
192 except exceptions.SSHExecCommandFailed:
193 if self.should_pass:
194 return False
195 else:
196 return True
197 finally:
198 self.test_attempt += 1
199
200 def test_connection(self, should_pass=True, timeout=10, sleep_timer=1):
201 self.should_pass = should_pass
202 wait_until_true(
203 self._test_connection, timeout=timeout, sleep=sleep_timer)
204
205 def __exit__(self, type, value, traceback):
206 self.server_ssh.exec_command('sudo killall nc || killall nc')
Alex Katz5d1043b2021-08-03 10:21:43 +0300207 self.server_ssh.exec_command(
208 'sudo killall tail || killall tail || echo "True"')
Alex Katzbd2bfd42021-05-26 18:12:36 +0300209 self.client_ssh.exec_command('sudo killall nc || killall nc')
Alex Katz5d1043b2021-08-03 10:21:43 +0300210 self.client_ssh.exec_command(
211 'sudo killall tail || killall tail || echo "True"')