blob: 5d6a26ae7996764e43337b5cf88a3e465b6f9494 [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
Rodolfo Alonso Hernandez80df3662025-08-28 09:04:14 +000028from neutron_lib._i18n import _
Alex Katz5684d5e2022-08-15 23:50:24 +030029from oslo_log import log
Maciej Józefczyk328edc82019-09-16 14:05:48 +000030from tempest.lib import exceptions
Brian Haley33ef4602018-04-26 14:37:49 -040031
Eduardo Olivares1f665d82022-02-14 17:22:54 +010032from neutron_tempest_plugin import config
33
Rodolfo Alonso Hernandez0adf8a22020-06-11 11:28:25 +000034
zheng.yong74e760a2019-05-22 14:16:14 +080035SCHEMA_PORT_MAPPING = {
36 "http": 80,
37 "https": 443,
38}
Eduardo Olivares1f665d82022-02-14 17:22:54 +010039CONF = config.CONF
Alex Katz5684d5e2022-08-15 23:50:24 +030040LOG = log.getLogger(__name__)
zheng.yong74e760a2019-05-22 14:16:14 +080041
Chandan Kumar5e619872017-09-07 22:23:55 +053042
43class classproperty(object):
44 def __init__(self, f):
45 self.func = f
46
47 def __get__(self, obj, owner):
Chandan Kumar667d3d32017-09-22 12:24:06 +053048 return self.func(owner)
49
Chandan Kumar5e619872017-09-07 22:23:55 +053050
51class WaitTimeout(Exception):
52 """Default exception coming from wait_until_true() function."""
53
54
55class LockWithTimer(object):
56 def __init__(self, threshold):
57 self._threshold = threshold
58 self.timestamp = 0
59 self._lock = threading.Lock()
60
61 def acquire(self):
62 return self._lock.acquire(False)
63
64 def release(self):
65 return self._lock.release()
66
67 def time_to_wait(self):
68 return self.timestamp - time.time() + self._threshold
69
Chandan Kumar667d3d32017-09-22 12:24:06 +053070
Chandan Kumar5e619872017-09-07 22:23:55 +053071def wait_until_true(predicate, timeout=60, sleep=1, exception=None):
Brian Haleyae328b92018-10-09 19:51:54 -040072 """Wait until callable predicate is evaluated as True
73
Chandan Kumar5e619872017-09-07 22:23:55 +053074 :param predicate: Callable deciding whether waiting should continue.
Elod Illesf2e985e2023-11-06 19:30:29 +010075 Best practice is to instantiate predicate with functools.partial()
Chandan Kumar5e619872017-09-07 22:23:55 +053076 :param timeout: Timeout in seconds how long should function wait.
77 :param sleep: Polling interval for results in seconds.
78 :param exception: Exception instance to raise on timeout. If None is passed
79 (default) then WaitTimeout exception is raised.
80 """
Pavlo Shchelokovskyyfed6d322025-04-22 10:30:23 +000081 start_time = time.time()
82 while not predicate():
83 elapsed_time = time.time() - start_time
84 if elapsed_time > timeout:
85 raise exception if exception else WaitTimeout(
86 _("Timed out after %d seconds") % timeout
87 )
88 time.sleep(sleep)
Brian Haleyba800452017-12-14 10:30:48 -050089
90
Federico Ressi0e04f8f2018-10-24 12:19:05 +020091def override_class(overriden_class, overrider_class):
92 """Override class definition with a MixIn class
93
94 If overriden_class is not a subclass of overrider_class then it creates
95 a new class that has as bases overrider_class and overriden_class.
96 """
97
98 if not issubclass(overriden_class, overrider_class):
99 name = overriden_class.__name__
100 bases = (overrider_class, overriden_class)
101 overriden_class = type(name, bases, {})
102 return overriden_class
zheng.yong74e760a2019-05-22 14:16:14 +0800103
104
105def normalize_url(url):
106 """Normalize url without port with schema default port
107
108 """
109 parse_result = urlparse.urlparse(url)
110 (scheme, netloc, url, params, query, fragment) = parse_result
111 port = parse_result.port
112 if scheme in SCHEMA_PORT_MAPPING and not port:
113 netloc = netloc + ":" + str(SCHEMA_PORT_MAPPING[scheme])
114 return urlparse.urlunparse((scheme, netloc, url, params, query, fragment))
Maciej Józefczyk328edc82019-09-16 14:05:48 +0000115
116
117def kill_nc_process(ssh_client):
118 cmd = "killall -q nc"
119 try:
120 ssh_client.exec_command(cmd)
121 except exceptions.SSHExecCommandFailed:
122 pass
123
124
Slawek Kaplonskifd4141f2020-03-14 14:34:00 +0100125def process_is_running(ssh_client, process_name):
126 try:
127 ssh_client.exec_command("pidof %s" % process_name)
128 return True
129 except exceptions.SSHExecCommandFailed:
130 return False
131
132
Alex Katzbd2bfd42021-05-26 18:12:36 +0300133class StatefulConnection:
134 """Class to test connection that should remain opened
135
136 Can be used to perform some actions while the initiated connection
137 remain opened
138 """
139
140 def __init__(self, client_ssh, server_ssh, target_ip, target_port):
141 self.client_ssh = client_ssh
142 self.server_ssh = server_ssh
143 self.ip = target_ip
144 self.port = target_port
145 self.connection_started = False
146 self.test_attempt = 0
Alex Katz305ea4a2022-08-10 19:47:03 +0300147 self.test_timeout = 10
148 self.test_sleep = 1
Alex Katzbd2bfd42021-05-26 18:12:36 +0300149
150 def __enter__(self):
151 return self
152
153 @property
154 def test_str(self):
155 return 'attempt_{}'.format(str(self.test_attempt).zfill(3))
156
157 def _start_connection(self):
Eduardo Olivares1f665d82022-02-14 17:22:54 +0100158 if CONF.neutron_plugin_options.default_image_is_advanced:
159 server_exec_method = self.server_ssh.execute_script
160 client_exec_method = self.client_ssh.execute_script
161 else:
162 server_exec_method = self.server_ssh.exec_command
163 client_exec_method = self.client_ssh.exec_command
164
Alex Katzbd2bfd42021-05-26 18:12:36 +0300165 self.server_ssh.exec_command(
166 'echo "{}" > input.txt'.format(self.test_str))
Alex Katz305ea4a2022-08-10 19:47:03 +0300167 server_exec_method('tail -f input.txt | sudo nc -lp '
Alex Katzbd2bfd42021-05-26 18:12:36 +0300168 '{} &> output.txt &'.format(self.port))
169 self.client_ssh.exec_command(
170 'echo "{}" > input.txt'.format(self.test_str))
Alex Katz305ea4a2022-08-10 19:47:03 +0300171 client_exec_method('tail -f input.txt | sudo nc {} {} &>'
Alex Katzbd2bfd42021-05-26 18:12:36 +0300172 'output.txt &'.format(self.ip, self.port))
173
Alex Katz305ea4a2022-08-10 19:47:03 +0300174 def _nc_is_running(self):
175 server = process_is_running(self.server_ssh, 'nc')
176 client = process_is_running(self.client_ssh, 'nc')
177 if client and server:
178 return True
179 else:
180 return False
181
Alex Katzbd2bfd42021-05-26 18:12:36 +0300182 def _test_connection(self):
183 if not self.connection_started:
184 self._start_connection()
185 else:
186 self.server_ssh.exec_command(
187 'echo "{}" >> input.txt'.format(self.test_str))
188 self.client_ssh.exec_command(
189 'echo "{}" >> input.txt & sleep 1'.format(self.test_str))
Alex Katz305ea4a2022-08-10 19:47:03 +0300190 wait_until_true(self._nc_is_running,
191 timeout=self.test_timeout,
192 sleep=self.test_sleep)
Alex Katzbd2bfd42021-05-26 18:12:36 +0300193 try:
Alex Katz5684d5e2022-08-15 23:50:24 +0300194 LOG.info("Checking connectivity between server and client -"
Takashi Kajinami435ff6f2024-11-16 15:33:27 +0900195 " attempt %d", self.test_attempt)
Alex Katzbd2bfd42021-05-26 18:12:36 +0300196 self.server_ssh.exec_command(
197 'grep {} output.txt'.format(self.test_str))
198 self.client_ssh.exec_command(
199 'grep {} output.txt'.format(self.test_str))
200 if not self.should_pass:
Takashi Kajinami435ff6f2024-11-16 15:33:27 +0900201 LOG.warning("attempt %d succeed while it should fail",
202 self.test_attempt)
Alex Katzbd2bfd42021-05-26 18:12:36 +0300203 return False
204 else:
205 if not self.connection_started:
206 self.connection_started = True
Takashi Kajinami435ff6f2024-11-16 15:33:27 +0900207 LOG.info("attempt %d succeed as it expected",
208 self.test_attempt)
Alex Katzbd2bfd42021-05-26 18:12:36 +0300209 return True
210 except exceptions.SSHExecCommandFailed:
211 if self.should_pass:
Takashi Kajinami435ff6f2024-11-16 15:33:27 +0900212 LOG.warning("attempt %d failed while it should pass",
213 self.test_attempt)
Alex Katzbd2bfd42021-05-26 18:12:36 +0300214 return False
215 else:
Takashi Kajinami435ff6f2024-11-16 15:33:27 +0900216 LOG.info("attempt %d failed as it expected",
217 self.test_attempt)
Alex Katzbd2bfd42021-05-26 18:12:36 +0300218 return True
219 finally:
220 self.test_attempt += 1
221
222 def test_connection(self, should_pass=True, timeout=10, sleep_timer=1):
223 self.should_pass = should_pass
Alex Katz305ea4a2022-08-10 19:47:03 +0300224 self.test_timeout = timeout
225 self.test_sleep = sleep_timer
226 wait_until_true(self._test_connection,
227 timeout=self.test_timeout,
228 sleep=self.test_sleep)
Alex Katzbd2bfd42021-05-26 18:12:36 +0300229
230 def __exit__(self, type, value, traceback):
Eduardo Olivares1f665d82022-02-14 17:22:54 +0100231 self.server_ssh.exec_command('sudo killall nc || killall nc || '
232 'echo "True"')
Alex Katz5d1043b2021-08-03 10:21:43 +0300233 self.server_ssh.exec_command(
234 'sudo killall tail || killall tail || echo "True"')
Eduardo Olivares1f665d82022-02-14 17:22:54 +0100235 self.client_ssh.exec_command('sudo killall nc || killall nc || '
236 'echo "True"')
Alex Katz5d1043b2021-08-03 10:21:43 +0300237 self.client_ssh.exec_command(
238 'sudo killall tail || killall tail || echo "True"')