| 1 |
# Copyright 2020, TUF contributors |
| 2 |
# SPDX-License-Identifier: MIT OR Apache-2.0 |
| 3 |
|
| 4 |
""" |
| 5 |
<Program Name> |
| 6 |
utils.py |
| 7 |
|
| 8 |
<Started> |
| 9 |
August 3, 2020. |
| 10 |
|
| 11 |
<Author> |
| 12 |
Jussi Kukkonen |
| 13 |
|
| 14 |
<Copyright> |
| 15 |
See LICENSE-MIT OR LICENSE for licensing information. |
| 16 |
|
| 17 |
<Purpose> |
| 18 |
Provide common utilities for TUF tests |
| 19 |
""" |
| 20 |
|
| 21 |
from __future__ import annotations |
| 22 |
|
| 23 |
import argparse |
| 24 |
import errno |
| 25 |
import logging |
| 26 |
import os |
| 27 |
import queue |
| 28 |
import socket |
| 29 |
import subprocess |
| 30 |
import sys |
| 31 |
import threading |
| 32 |
import time |
| 33 |
import warnings |
| 34 |
from contextlib import contextmanager |
| 35 |
from typing import IO, TYPE_CHECKING, Any |
| 36 |
|
| 37 |
if TYPE_CHECKING: |
| 38 |
import unittest |
| 39 |
from collections.abc import Callable, Iterator |
| 40 |
|
| 41 |
logger = logging.getLogger(__name__) |
| 42 |
|
| 43 |
# May be used to reliably read other files in tests dir regardless of cwd |
| 44 |
TESTS_DIR = os.path.dirname(os.path.realpath(__file__)) |
| 45 |
|
| 46 |
# Used when forming URLs on the client side |
| 47 |
TEST_HOST_ADDRESS = "127.0.0.1" |
| 48 |
|
| 49 |
|
| 50 |
# Test runner decorator: Runs the test as a set of N SubTests, |
| 51 |
# (where N is number of items in dataset), feeding the actual test |
| 52 |
# function one test case at a time |
| 53 |
def run_sub_tests_with_dataset( |
| 54 |
dataset: dict[str, Any], |
| 55 |
) -> Callable[[Callable], Callable]: |
| 56 |
"""Decorator starting a unittest.TestCase.subtest() for each of the |
| 57 |
cases in dataset""" |
| 58 |
|
| 59 |
def real_decorator( |
| 60 |
function: Callable[[unittest.TestCase, Any], None], |
| 61 |
) -> Callable[[unittest.TestCase], None]: |
| 62 |
def wrapper(test_cls: unittest.TestCase) -> None: |
| 63 |
for case, data in dataset.items(): |
| 64 |
with test_cls.subTest(case=case): |
| 65 |
# Save case name for future reference |
| 66 |
test_cls.case_name = case.replace(" ", "_") |
| 67 |
function(test_cls, data) |
| 68 |
|
| 69 |
return wrapper |
| 70 |
|
| 71 |
return real_decorator |
| 72 |
|
| 73 |
|
| 74 |
class TestServerProcessError(Exception): |
| 75 |
def __init__(self, value: str = "TestServerProcess") -> None: |
| 76 |
super().__init__() |
| 77 |
self.value = value |
| 78 |
|
| 79 |
def __str__(self) -> str: |
| 80 |
return repr(self.value) |
| 81 |
|
| 82 |
|
| 83 |
@contextmanager |
| 84 |
def ignore_deprecation_warnings(module: str) -> Iterator[None]: |
| 85 |
with warnings.catch_warnings(): |
| 86 |
warnings.filterwarnings( |
| 87 |
"ignore", category=DeprecationWarning, module=module |
| 88 |
) |
| 89 |
yield |
| 90 |
|
| 91 |
|
| 92 |
# Wait until host:port accepts connections. |
| 93 |
# Raises TimeoutError if this does not happen within timeout seconds |
| 94 |
# There are major differences between operating systems on how this works |
| 95 |
# but the current blocking connect() seems to work fast on Linux and seems |
| 96 |
# to at least work on Windows (ECONNREFUSED unfortunately has a 2 second |
| 97 |
# timeout on Windows) |
| 98 |
def wait_for_server( |
| 99 |
host: str, server: str, port: int, timeout: int = 10 |
| 100 |
) -> None: |
| 101 |
"""Wait for server start until timeout is reached or server has started""" |
| 102 |
start = time.time() |
| 103 |
remaining_timeout = timeout |
| 104 |
succeeded = False |
| 105 |
while not succeeded and remaining_timeout > 0: |
| 106 |
try: |
| 107 |
sock: socket.socket | None = socket.socket( |
| 108 |
socket.AF_INET, socket.SOCK_STREAM |
| 109 |
) |
| 110 |
assert sock is not None |
| 111 |
sock.settimeout(remaining_timeout) |
| 112 |
sock.connect((host, port)) |
| 113 |
succeeded = True |
| 114 |
except TimeoutError: |
| 115 |
pass |
| 116 |
except OSError as e: |
| 117 |
# ECONNREFUSED is expected while the server is not started |
| 118 |
if e.errno != errno.ECONNREFUSED: |
| 119 |
logger.warning( |
| 120 |
"Unexpected error while waiting for server: %s", str(e) |
| 121 |
) |
| 122 |
# Avoid pegging a core just for this |
| 123 |
time.sleep(0.01) |
| 124 |
finally: |
| 125 |
if sock: |
| 126 |
sock.close() |
| 127 |
sock = None |
| 128 |
remaining_timeout = int(timeout - (time.time() - start)) |
| 129 |
|
| 130 |
if not succeeded: |
| 131 |
raise TimeoutError( |
| 132 |
"Could not connect to the " + server + " on port " + str(port) + "!" |
| 133 |
) |
| 134 |
|
| 135 |
|
| 136 |
def configure_test_logging(argv: list[str]) -> None: |
| 137 |
"""Configure logger level for a certain test file""" |
| 138 |
# parse arguments but only handle '-v': argv may contain |
| 139 |
# other things meant for unittest argument parser |
| 140 |
parser = argparse.ArgumentParser(add_help=False) |
| 141 |
parser.add_argument("-v", "--verbose", action="count", default=0) |
| 142 |
args, _ = parser.parse_known_args(argv) |
| 143 |
|
| 144 |
if args.verbose <= 1: |
| 145 |
# 0 and 1 both mean ERROR: this way '-v' makes unittest print test |
| 146 |
# names without increasing log level |
| 147 |
loglevel = logging.ERROR |
| 148 |
elif args.verbose == 2: |
| 149 |
loglevel = logging.WARNING |
| 150 |
elif args.verbose == 3: |
| 151 |
loglevel = logging.INFO |
| 152 |
else: |
| 153 |
loglevel = logging.DEBUG |
| 154 |
|
| 155 |
logging.basicConfig(level=loglevel) |
| 156 |
|
| 157 |
|
| 158 |
def cleanup_metadata_dir(path: str) -> None: |
| 159 |
"""Delete the local metadata dir""" |
| 160 |
with os.scandir(path) as it: |
| 161 |
for entry in it: |
| 162 |
if entry.name == "root_history": |
| 163 |
cleanup_metadata_dir(entry.path) |
| 164 |
elif entry.name.endswith(".json"): |
| 165 |
os.remove(entry.path) |
| 166 |
else: |
| 167 |
raise ValueError(f"Unexpected local metadata file {entry.path}") |
| 168 |
|
| 169 |
|
| 170 |
class TestServerProcess: |
| 171 |
"""Helper class used to create a child process with the subprocess.Popen |
| 172 |
object and use a thread-safe Queue structure for logging. |
| 173 |
|
| 174 |
Args: |
| 175 |
log: Logger which will be used for logging. |
| 176 |
server: Path to the server to run in the subprocess. |
| 177 |
timeout: Time in seconds in which the server should start or otherwise |
| 178 |
TimeoutError error will be raised. |
| 179 |
popen_cwd: Current working directory used when instancing a |
| 180 |
subprocess.Popen object. |
| 181 |
extra_cmd_args: Additional arguments for the command which will start |
| 182 |
the subprocess. More precisely: |
| 183 |
"python -u <path_to_server> <port> <extra_cmd_args>". |
| 184 |
If no list is provided, an empty list ("[]") will be assigned to it. |
| 185 |
""" |
| 186 |
|
| 187 |
def __init__( |
| 188 |
self, |
| 189 |
log: logging.Logger, |
| 190 |
server: str = os.path.join(TESTS_DIR, "simple_server.py"), |
| 191 |
timeout: int = 10, |
| 192 |
popen_cwd: str = ".", |
| 193 |
extra_cmd_args: list[str] | None = None, |
| 194 |
): |
| 195 |
self.server = server |
| 196 |
self.__logger = log |
| 197 |
# Stores popped messages from the queue. |
| 198 |
self.__logged_messages: list[str] = [] |
| 199 |
self.__server_process: subprocess.Popen | None = None |
| 200 |
self._log_queue: queue.Queue | None = None |
| 201 |
self.port = -1 |
| 202 |
if extra_cmd_args is None: |
| 203 |
extra_cmd_args = [] |
| 204 |
|
| 205 |
try: |
| 206 |
self._start_server(timeout, extra_cmd_args, popen_cwd) |
| 207 |
wait_for_server("localhost", self.server, self.port, timeout) |
| 208 |
except Exception as e: |
| 209 |
# Clean the resources and log the server errors if any exists. |
| 210 |
self.clean() |
| 211 |
raise e |
| 212 |
|
| 213 |
def _start_server( |
| 214 |
self, timeout: int, extra_cmd_args: list[str], popen_cwd: str |
| 215 |
) -> None: |
| 216 |
""" |
| 217 |
Start the server subprocess and a thread |
| 218 |
responsible to redirect stdout/stderr to the Queue. |
| 219 |
Waits for the port message maximum timeout seconds. |
| 220 |
""" |
| 221 |
|
| 222 |
self._start_process(extra_cmd_args, popen_cwd) |
| 223 |
self._start_redirect_thread() |
| 224 |
|
| 225 |
self._wait_for_port(timeout) |
| 226 |
|
| 227 |
self.__logger.info("%s serving on %d", self.server, self.port) |
| 228 |
|
| 229 |
def _start_process(self, extra_cmd_args: list[str], popen_cwd: str) -> None: |
| 230 |
"""Starts the process running the server.""" |
| 231 |
|
| 232 |
# The "-u" option forces stdin, stdout and stderr to be unbuffered. |
| 233 |
command = [sys.executable, "-u", self.server, *extra_cmd_args] |
| 234 |
|
| 235 |
# Reusing one subprocess in multiple tests, but split up the logs |
| 236 |
# for each. |
| 237 |
self.__server_process = subprocess.Popen( |
| 238 |
command, |
| 239 |
stdout=subprocess.PIPE, |
| 240 |
stderr=subprocess.STDOUT, |
| 241 |
cwd=popen_cwd, |
| 242 |
) |
| 243 |
|
| 244 |
def _start_redirect_thread(self) -> None: |
| 245 |
"""Starts a thread redirecting the stdout/stderr to the Queue.""" |
| 246 |
|
| 247 |
assert isinstance(self.__server_process, subprocess.Popen) |
| 248 |
# Run log_queue_worker() in a thread. |
| 249 |
# The thread will exit when the child process dies. |
| 250 |
self._log_queue = queue.Queue() |
| 251 |
log_thread = threading.Thread( |
| 252 |
target=self._log_queue_worker, |
| 253 |
args=(self.__server_process.stdout, self._log_queue), |
| 254 |
) |
| 255 |
|
| 256 |
# "daemon = True" means the thread won't interfere with the |
| 257 |
# process exit. |
| 258 |
log_thread.daemon = True |
| 259 |
log_thread.start() |
| 260 |
|
| 261 |
@staticmethod |
| 262 |
def _log_queue_worker(stream: IO, line_queue: queue.Queue) -> None: |
| 263 |
""" |
| 264 |
Worker function to run in a separate thread. |
| 265 |
Reads from 'stream', puts lines in a Queue (Queue is thread-safe). |
| 266 |
""" |
| 267 |
|
| 268 |
while True: |
| 269 |
# readline() is a blocking operation. |
| 270 |
# decode to push a string in the queue instead of 8-bit bytes. |
| 271 |
log_line = stream.readline().decode("utf-8") |
| 272 |
line_queue.put(log_line) |
| 273 |
|
| 274 |
if len(log_line) == 0: |
| 275 |
# This is the end of the stream meaning the server process |
| 276 |
# has exited. |
| 277 |
stream.close() |
| 278 |
break |
| 279 |
|
| 280 |
def _wait_for_port(self, timeout: int) -> None: |
| 281 |
""" |
| 282 |
Validates the first item from the Queue against the port message. |
| 283 |
If validation is successful, self.port is set. |
| 284 |
Raises TestServerProcessError if the process has exited or |
| 285 |
TimeoutError if no message was found within timeout seconds. |
| 286 |
""" |
| 287 |
|
| 288 |
assert isinstance(self.__server_process, subprocess.Popen) |
| 289 |
assert isinstance(self._log_queue, queue.Queue) |
| 290 |
# We have hardcoded the message we expect on a successful server |
| 291 |
# startup. This message should be the first message sent by the server! |
| 292 |
expected_msg = "bind succeeded, server port is: " |
| 293 |
try: |
| 294 |
line = self._log_queue.get(timeout=timeout) |
| 295 |
if len(line) == 0: |
| 296 |
# The process has exited. |
| 297 |
raise TestServerProcessError( |
| 298 |
self.server |
| 299 |
+ " exited unexpectedly " |
| 300 |
+ "with code " |
| 301 |
+ str(self.__server_process.poll()) |
| 302 |
+ "!" |
| 303 |
) |
| 304 |
|
| 305 |
if line.startswith(expected_msg): |
| 306 |
self.port = int(line[len(expected_msg) :]) |
| 307 |
else: |
| 308 |
# An exception or some other message is printed from the server. |
| 309 |
self.__logged_messages.append(line) |
| 310 |
# Check if more lines are logged. |
| 311 |
self.flush_log() |
| 312 |
raise TestServerProcessError( |
| 313 |
self.server |
| 314 |
+ " did not print port " |
| 315 |
+ "message as first stdout line as expected!" |
| 316 |
) |
| 317 |
except queue.Empty as e: |
| 318 |
raise TimeoutError( |
| 319 |
"Failure during " + self.server + " startup!" |
| 320 |
) from e |
| 321 |
|
| 322 |
def _kill_server_process(self) -> None: |
| 323 |
"""Kills the server subprocess if it's running.""" |
| 324 |
|
| 325 |
assert isinstance(self.__server_process, subprocess.Popen) |
| 326 |
if self.is_process_running(): |
| 327 |
self.__logger.info( |
| 328 |
"Server process %d terminated", self.__server_process.pid |
| 329 |
) |
| 330 |
self.__server_process.kill() |
| 331 |
self.__server_process.wait() |
| 332 |
|
| 333 |
def flush_log(self) -> None: |
| 334 |
"""Flushes the log lines from the logging queue.""" |
| 335 |
|
| 336 |
assert isinstance(self._log_queue, queue.Queue) |
| 337 |
while True: |
| 338 |
# Get lines from log_queue |
| 339 |
try: |
| 340 |
line = self._log_queue.get(block=False) |
| 341 |
if len(line) > 0: |
| 342 |
self.__logged_messages.append(line) |
| 343 |
except queue.Empty: |
| 344 |
# No more lines are logged in the queue. |
| 345 |
break |
| 346 |
|
| 347 |
if len(self.__logged_messages) > 0: |
| 348 |
title = "Test server (" + self.server + ") output:\n" |
| 349 |
message = [title, *self.__logged_messages] |
| 350 |
self.__logger.info("| ".join(message)) |
| 351 |
self.__logged_messages = [] |
| 352 |
|
| 353 |
def clean(self) -> None: |
| 354 |
""" |
| 355 |
Kills the subprocess and closes the TempFile. |
| 356 |
Calls flush_log to check for logged information, but not yet flushed. |
| 357 |
""" |
| 358 |
|
| 359 |
# If there is anything logged, flush it before closing the resources. |
| 360 |
self.flush_log() |
| 361 |
|
| 362 |
self._kill_server_process() |
| 363 |
|
| 364 |
def is_process_running(self) -> bool: |
| 365 |
assert isinstance(self.__server_process, subprocess.Popen) |
| 366 |
return self.__server_process.poll() is None |