3 # Copyright (C) 2022 Jérémie Galarneau <jeremie.galarneau@efficios.com>
5 # SPDX-License-Identifier: GPL-2.0-only
8 from types
import FrameType
9 from typing
import Callable
, Iterator
, Optional
, Tuple
, List
, Generator
25 class TemporaryDirectory
:
26 def __init__(self
, prefix
):
28 self
._directory
_path
= tempfile
.mkdtemp(prefix
=prefix
)
31 shutil
.rmtree(self
._directory
_path
, ignore_errors
=True)
35 # type: () -> pathlib.Path
36 return pathlib
.Path(self
._directory
_path
)
39 class _SignalWaitQueue
:
41 Utility class useful to wait for a signal before proceeding.
43 Simply register the `signal` method as the handler for the signal you are
44 interested in and call `wait_for_signal` to wait for its reception.
47 signal.signal(signal.SIGWHATEVER, queue.signal)
49 Waiting for the signal:
50 queue.wait_for_signal()
54 self
._queue
= queue
.Queue() # type: queue.Queue
59 frame
, # type: Optional[FrameType]
61 self
._queue
.put_nowait(signal_number
)
63 def wait_for_signal(self
):
64 self
._queue
.get(block
=True)
66 @contextlib.contextmanager
67 def intercept_signal(self
, signal_number
):
68 # type: (int) -> Generator[None, None, None]
69 original_handler
= signal
.getsignal(signal_number
)
70 signal
.signal(signal_number
, self
.signal
)
74 # Restore the original signal handler and forward the exception.
77 signal
.signal(signal_number
, original_handler
)
80 class WaitTraceTestApplication
:
82 Create an application that waits before tracing. This allows a test to
83 launch an application, get its PID, and get it to start tracing when it
84 has completed its setup.
89 binary_path
, # type: pathlib.Path
90 event_count
, # type: int
91 environment
, # type: Environment
92 wait_time_between_events_us
=0, # type: int
94 self
._environment
= environment
# type: Environment
96 # The test application currently produces 5 different events per iteration.
97 raise ValueError("event count must be a multiple of 5")
98 self
._iteration
_count
= int(event_count
/ 5) # type: int
99 # File that the application will wait to see before tracing its events.
100 self
._app
_start
_tracing
_file
_path
= pathlib
.Path(
103 suffix
="_start_tracing",
104 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
107 self
._has
_returned
= False
109 test_app_env
= os
.environ
.copy()
110 test_app_env
["LTTNG_HOME"] = str(environment
.lttng_home_location
)
111 # Make sure the app is blocked until it is properly registered to
112 # the session daemon.
113 test_app_env
["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
115 # File that the application will create to indicate it has completed its initialization.
116 app_ready_file_path
= tempfile
.mktemp(
119 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
122 test_app_args
= [str(binary_path
)]
123 test_app_args
.extend(
125 "--iter {iteration_count} --create-in-main {app_ready_file_path} --wait-before-first-event {app_start_tracing_file_path} --wait {wait_time_between_events_us}".format(
126 iteration_count
=self
._iteration
_count
,
127 app_ready_file_path
=app_ready_file_path
,
128 app_start_tracing_file_path
=self
._app
_start
_tracing
_file
_path
,
129 wait_time_between_events_us
=wait_time_between_events_us
,
134 self
._process
= subprocess
.Popen(
137 ) # type: subprocess.Popen
139 # Wait for the application to create the file indicating it has fully
140 # initialized. Make sure the app hasn't crashed in order to not wait
143 if os
.path
.exists(app_ready_file_path
):
146 if self
._process
.poll() is not None:
147 # Application has unexepectedly returned.
149 "Test application has unexepectedly returned during its initialization with return code `{return_code}`".format(
150 return_code
=self
._process
.returncode
158 if self
._process
.poll() is not None:
159 # Application has unexepectedly returned.
161 "Test application has unexepectedly before tracing with return code `{return_code}`".format(
162 return_code
=self
._process
.returncode
165 open(self
._compat
_open
_path
(self
._app
_start
_tracing
_file
_path
), mode
="x")
167 def wait_for_exit(self
):
169 if self
._process
.wait() != 0:
171 "Test application has exit with return code `{return_code}`".format(
172 return_code
=self
._process
.returncode
175 self
._has
_returned
= True
180 return self
._process
.pid
183 def _compat_open_path(path
):
184 # type: (pathlib.Path) -> pathlib.Path | str
186 The builtin open() in python >= 3.6 expects a path-like object while
187 prior versions expect a string or bytes object. Return the correct type
188 based on the presence of the "__fspath__" attribute specified in PEP-519.
190 if hasattr(path
, "__fspath__"):
196 if not self
._has
_returned
:
197 # This is potentially racy if the pid has been recycled. However,
198 # we can't use pidfd_open since it is only available in python >= 3.9.
203 class TraceTestApplication
:
205 Create an application that emits events as soon as it is launched. In most
206 scenarios, it is preferable to use a WaitTraceTestApplication.
209 def __init__(self
, binary_path
, environment
):
210 # type: (pathlib.Path, Environment)
211 self
._environment
= environment
# type: Environment
212 self
._has
_returned
= False
214 test_app_env
= os
.environ
.copy()
215 test_app_env
["LTTNG_HOME"] = str(environment
.lttng_home_location
)
216 # Make sure the app is blocked until it is properly registered to
217 # the session daemon.
218 test_app_env
["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
220 test_app_args
= [str(binary_path
)]
222 self
._process
= subprocess
.Popen(
223 test_app_args
, env
=test_app_env
224 ) # type: subprocess.Popen
226 def wait_for_exit(self
):
228 if self
._process
.wait() != 0:
230 "Test application has exit with return code `{return_code}`".format(
231 return_code
=self
._process
.returncode
234 self
._has
_returned
= True
237 if not self
._has
_returned
:
238 # This is potentially racy if the pid has been recycled. However,
239 # we can't use pidfd_open since it is only available in python >= 3.9.
244 class ProcessOutputConsumer(threading
.Thread
, logger
._Logger
):
247 process
, # type: subprocess.Popen
249 log
, # type: Callable[[str], None]
251 threading
.Thread
.__init
__(self
)
253 logger
._Logger
.__init
__(self
, log
)
254 self
._process
= process
258 while self
._process
.poll() is None:
259 assert self
._process
.stdout
260 line
= self
._process
.stdout
.readline().decode("utf-8").replace("\n", "")
262 self
._log
("{prefix}: {line}".format(prefix
=self
._prefix
, line
=line
))
265 # Generate a temporary environment in which to execute a test.
266 class _Environment(logger
._Logger
):
269 with_sessiond
, # type: bool
270 log
=None, # type: Optional[Callable[[str], None]]
272 super().__init
__(log
)
273 signal
.signal(signal
.SIGTERM
, self
._handle
_termination
_signal
)
274 signal
.signal(signal
.SIGINT
, self
._handle
_termination
_signal
)
276 # Assumes the project's hierarchy to this file is:
277 # tests/utils/python/this_file
278 self
._project
_root
= (
279 pathlib
.Path(__file__
).absolute().parents
[3]
280 ) # type: pathlib.Path
281 self
._lttng
_home
= TemporaryDirectory(
282 "lttng_test_env_home"
283 ) # type: Optional[TemporaryDirectory]
286 self
._launch
_lttng
_sessiond
() if with_sessiond
else None
287 ) # type: Optional[subprocess.Popen[bytes]]
290 def lttng_home_location(self
):
291 # type: () -> pathlib.Path
292 if self
._lttng
_home
is None:
293 raise RuntimeError("Attempt to access LTTng home after clean-up")
294 return self
._lttng
_home
.path
297 def lttng_client_path(self
):
298 # type: () -> pathlib.Path
299 return self
._project
_root
/ "src" / "bin" / "lttng" / "lttng"
301 def create_temporary_directory(self
, prefix
=None):
302 # type: (Optional[str]) -> pathlib.Path
303 # Simply return a path that is contained within LTTNG_HOME; it will
304 # be destroyed when the temporary home goes out of scope.
305 assert self
._lttng
_home
308 prefix
="tmp" if prefix
is None else prefix
,
309 dir=str(self
._lttng
_home
.path
),
313 # Unpack a list of environment variables from a string
314 # such as "HELLO=is_it ME='/you/are/looking/for'"
316 def _unpack_env_vars(env_vars_string
):
317 # type: (str) -> List[Tuple[str, str]]
319 for var
in shlex
.split(env_vars_string
):
320 equal_position
= var
.find("=")
321 # Must have an equal sign and not end with an equal sign
322 if equal_position
== -1 or equal_position
== len(var
) - 1:
324 "Invalid sessiond environment variable: `{}`".format(var
)
327 var_name
= var
[0:equal_position
]
328 var_value
= var
[equal_position
+ 1 :]
330 var_value
= var_value
.replace("'", "")
331 var_value
= var_value
.replace('"', "")
332 unpacked_vars
.append((var_name
, var_value
))
336 def _launch_lttng_sessiond(self
):
337 # type: () -> Optional[subprocess.Popen]
338 is_64bits_host
= sys
.maxsize
> 2**32
341 self
._project
_root
/ "src" / "bin" / "lttng-sessiond" / "lttng-sessiond"
343 consumerd_path_option_name
= "--consumerd{bitness}-path".format(
344 bitness
="64" if is_64bits_host
else "32"
347 self
._project
_root
/ "src" / "bin" / "lttng-consumerd" / "lttng-consumerd"
350 no_sessiond_var
= os
.environ
.get("TEST_NO_SESSIOND")
351 if no_sessiond_var
and no_sessiond_var
== "1":
352 # Run test without a session daemon; the user probably
353 # intends to run one under gdb for example.
356 # Setup the session daemon's environment
357 sessiond_env_vars
= os
.environ
.get("LTTNG_SESSIOND_ENV_VARS")
358 sessiond_env
= os
.environ
.copy()
359 if sessiond_env_vars
:
360 self
._log
("Additional lttng-sessiond environment variables:")
361 additional_vars
= self
._unpack
_env
_vars
(sessiond_env_vars
)
362 for var_name
, var_value
in additional_vars
:
363 self
._log
(" {name}={value}".format(name
=var_name
, value
=var_value
))
364 sessiond_env
[var_name
] = var_value
366 sessiond_env
["LTTNG_SESSION_CONFIG_XSD_PATH"] = str(
367 self
._project
_root
/ "src" / "common"
370 assert self
._lttng
_home
is not None
371 sessiond_env
["LTTNG_HOME"] = str(self
._lttng
_home
.path
)
373 wait_queue
= _SignalWaitQueue()
374 with wait_queue
.intercept_signal(signal
.SIGUSR1
):
376 "Launching session daemon with LTTNG_HOME=`{home_dir}`".format(
377 home_dir
=str(self
._lttng
_home
.path
)
380 process
= subprocess
.Popen(
383 consumerd_path_option_name
,
387 stdout
=subprocess
.PIPE
,
388 stderr
=subprocess
.STDOUT
,
392 if self
._logging
_function
:
393 self
._sessiond
_output
_consumer
= ProcessOutputConsumer(
394 process
, "lttng-sessiond", self
._logging
_function
395 ) # type: Optional[ProcessOutputConsumer]
396 self
._sessiond
_output
_consumer
.daemon
= True
397 self
._sessiond
_output
_consumer
.start()
399 # Wait for SIGUSR1, indicating the sessiond is ready to proceed
400 wait_queue
.wait_for_signal()
404 def _handle_termination_signal(self
, signal_number
, frame
):
405 # type: (int, Optional[FrameType]) -> None
407 "Killed by {signal_name} signal, cleaning-up".format(
408 signal_name
=signal
.strsignal(signal_number
)
413 def launch_wait_trace_test_application(self
, event_count
):
414 # type: (int) -> WaitTraceTestApplication
416 Launch an application that will wait before tracing `event_count` events.
418 return WaitTraceTestApplication(
429 def launch_trace_test_constructor_application(self
):
430 # type () -> TraceTestApplication
432 Launch an application that will trace from within constructors.
434 return TraceTestApplication(
439 / "gen-ust-events-constructor"
440 / "gen-ust-events-constructor",
444 # Clean-up managed processes
447 if self
._sessiond
and self
._sessiond
.poll() is None:
448 # The session daemon is alive; kill it.
450 "Killing session daemon (pid = {sessiond_pid})".format(
451 sessiond_pid
=self
._sessiond
.pid
455 self
._sessiond
.terminate()
456 self
._sessiond
.wait()
457 if self
._sessiond
_output
_consumer
:
458 self
._sessiond
_output
_consumer
.join()
459 self
._sessiond
_output
_consumer
= None
461 self
._log
("Session daemon killed")
462 self
._sessiond
= None
464 self
._lttng
_home
= None
470 @contextlib.contextmanager
471 def test_environment(with_sessiond
, log
=None):
472 # type: (bool, Optional[Callable[[str], None]]) -> Iterator[_Environment]
473 env
= _Environment(with_sessiond
, log
)