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
93 wait_before_exit
=False, # type: bool
94 wait_before_exit_file_path
=None, # type: Optional[pathlib.Path]
96 self
._environment
= environment
# type: Environment
97 self
._iteration
_count
= event_count
98 # File that the application will wait to see before tracing its events.
99 self
._app
_start
_tracing
_file
_path
= pathlib
.Path(
102 suffix
="_start_tracing",
103 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
106 # File that the application will create when all events have been emitted.
107 self
._app
_tracing
_done
_file
_path
= pathlib
.Path(
110 suffix
="_done_tracing",
111 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
115 if wait_before_exit
and wait_before_exit_file_path
is None:
116 wait_before_exit_file_path
= pathlib
.Path(
120 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
124 self
._has
_returned
= False
126 test_app_env
= os
.environ
.copy()
127 test_app_env
["LTTNG_HOME"] = str(environment
.lttng_home_location
)
128 # Make sure the app is blocked until it is properly registered to
129 # the session daemon.
130 test_app_env
["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
132 # File that the application will create to indicate it has completed its initialization.
133 app_ready_file_path
= tempfile
.mktemp(
136 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
139 test_app_args
= [str(binary_path
)]
140 test_app_args
.extend(["--iter", str(event_count
)])
141 test_app_args
.extend(
142 ["--sync-application-in-main-touch", str(app_ready_file_path
)]
144 test_app_args
.extend(
145 ["--sync-before-first-event", str(self
._app
_start
_tracing
_file
_path
)]
147 test_app_args
.extend(
148 ["--sync-before-exit-touch", str(self
._app
_tracing
_done
_file
_path
)]
150 if wait_time_between_events_us
!= 0:
151 test_app_args
.extend(["--wait", str(wait_time_between_events_us
)])
153 self
._process
= subprocess
.Popen(
156 stdout
=subprocess
.PIPE
,
157 stderr
=subprocess
.STDOUT
,
158 ) # type: subprocess.Popen
160 # Wait for the application to create the file indicating it has fully
161 # initialized. Make sure the app hasn't crashed in order to not wait
163 self
._wait
_for
_file
_to
_be
_created
(pathlib
.Path(app_ready_file_path
))
165 def _wait_for_file_to_be_created(self
, sync_file_path
):
166 # type: (pathlib.Path) -> None
168 if os
.path
.exists(sync_file_path
):
171 if self
._process
.poll() is not None:
172 # Application has unexepectedly returned.
174 "Test application has unexepectedly returned while waiting for synchronization file to be created: sync_file=`{sync_file}`, return_code=`{return_code}`".format(
175 sync_file
=sync_file_path
, return_code
=self
._process
.returncode
183 if self
._process
.poll() is not None:
184 # Application has unexepectedly returned.
186 "Test application has unexepectedly before tracing with return code `{return_code}`".format(
187 return_code
=self
._process
.returncode
190 open(self
._compat
_open
_path
(self
._app
_start
_tracing
_file
_path
), mode
="x")
192 def wait_for_tracing_done(self
):
194 self
._wait
_for
_file
_to
_be
_created
(self
._app
_tracing
_done
_file
_path
)
196 def wait_for_exit(self
):
198 if self
._process
.wait() != 0:
200 "Test application has exit with return code `{return_code}`".format(
201 return_code
=self
._process
.returncode
204 self
._has
_returned
= True
209 return self
._process
.pid
212 def _compat_open_path(path
):
213 # type: (pathlib.Path) -> pathlib.Path | str
215 The builtin open() in python >= 3.6 expects a path-like object while
216 prior versions expect a string or bytes object. Return the correct type
217 based on the presence of the "__fspath__" attribute specified in PEP-519.
219 if hasattr(path
, "__fspath__"):
225 if not self
._has
_returned
:
226 # This is potentially racy if the pid has been recycled. However,
227 # we can't use pidfd_open since it is only available in python >= 3.9.
232 class WaitTraceTestApplicationGroup
:
235 environment
, # type: Environment
236 application_count
, # type: int
237 event_count
, # type: int
238 wait_time_between_events_us
=0, # type: int
239 wait_before_exit
=False, # type: bool
241 self
._wait
_before
_exit
_file
_path
= (
246 dir=_WaitTraceTestApplication
._compat
_open
_path
(
247 environment
.lttng_home_location
257 for i
in range(application_count
):
258 new_app
= environment
.launch_wait_trace_test_application(
260 wait_time_between_events_us
,
262 self
._wait
_before
_exit
_file
_path
,
265 # Attach an output consumer to log the application's error output (if any).
266 if environment
._logging
_function
:
267 app_output_consumer
= ProcessOutputConsumer(
269 "app-{}".format(str(new_app
.vpid
)),
270 environment
._logging
_function
,
271 ) # type: Optional[ProcessOutputConsumer]
272 app_output_consumer
.daemon
= True
273 app_output_consumer
.start()
274 self
._consumers
.append(app_output_consumer
)
276 self
._apps
.append(new_app
)
280 for app
in self
._apps
:
284 self
, wait_for_apps
=False # type: bool
286 if self
._wait
_before
_exit
_file
_path
is None:
288 "Can't call exit on an application group created with `wait_before_exit=False`"
291 # Wait for apps to have produced all of their events so that we can
292 # cause the death of all apps to happen within a short time span.
293 for app
in self
._apps
:
294 app
.wait_for_tracing_done()
297 _WaitTraceTestApplication
._compat
_open
_path
(
298 self
._wait
_before
_exit
_file
_path
302 # Performed in two passes to allow tests to stress the unregistration of many applications.
303 # Waiting for each app to exit turn-by-turn would defeat the purpose here.
305 for app
in self
._apps
:
309 class _TraceTestApplication
:
311 Create an application that emits events as soon as it is launched. In most
312 scenarios, it is preferable to use a WaitTraceTestApplication.
315 def __init__(self
, binary_path
, environment
):
316 # type: (pathlib.Path, Environment)
317 self
._environment
= environment
# type: Environment
318 self
._has
_returned
= False
320 test_app_env
= os
.environ
.copy()
321 test_app_env
["LTTNG_HOME"] = str(environment
.lttng_home_location
)
322 # Make sure the app is blocked until it is properly registered to
323 # the session daemon.
324 test_app_env
["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
326 test_app_args
= [str(binary_path
)]
328 self
._process
= subprocess
.Popen(
329 test_app_args
, env
=test_app_env
330 ) # type: subprocess.Popen
332 def wait_for_exit(self
):
334 if self
._process
.wait() != 0:
336 "Test application has exit with return code `{return_code}`".format(
337 return_code
=self
._process
.returncode
340 self
._has
_returned
= True
343 if not self
._has
_returned
:
344 # This is potentially racy if the pid has been recycled. However,
345 # we can't use pidfd_open since it is only available in python >= 3.9.
350 class ProcessOutputConsumer(threading
.Thread
, logger
._Logger
):
353 process
, # type: subprocess.Popen
355 log
, # type: Callable[[str], None]
357 threading
.Thread
.__init
__(self
)
359 logger
._Logger
.__init
__(self
, log
)
360 self
._process
= process
364 while self
._process
.poll() is None:
365 assert self
._process
.stdout
366 line
= self
._process
.stdout
.readline().decode("utf-8").replace("\n", "")
368 self
._log
("{prefix}: {line}".format(prefix
=self
._prefix
, line
=line
))
371 # Generate a temporary environment in which to execute a test.
372 class _Environment(logger
._Logger
):
375 with_sessiond
, # type: bool
376 log
=None, # type: Optional[Callable[[str], None]]
378 super().__init
__(log
)
379 signal
.signal(signal
.SIGTERM
, self
._handle
_termination
_signal
)
380 signal
.signal(signal
.SIGINT
, self
._handle
_termination
_signal
)
382 # Assumes the project's hierarchy to this file is:
383 # tests/utils/python/this_file
384 self
._project
_root
= (
385 pathlib
.Path(__file__
).absolute().parents
[3]
386 ) # type: pathlib.Path
387 self
._lttng
_home
= TemporaryDirectory(
388 "lttng_test_env_home"
389 ) # type: Optional[TemporaryDirectory]
392 self
._launch
_lttng
_sessiond
() if with_sessiond
else None
393 ) # type: Optional[subprocess.Popen[bytes]]
396 def lttng_home_location(self
):
397 # type: () -> pathlib.Path
398 if self
._lttng
_home
is None:
399 raise RuntimeError("Attempt to access LTTng home after clean-up")
400 return self
._lttng
_home
.path
403 def lttng_client_path(self
):
404 # type: () -> pathlib.Path
405 return self
._project
_root
/ "src" / "bin" / "lttng" / "lttng"
407 def create_temporary_directory(self
, prefix
=None):
408 # type: (Optional[str]) -> pathlib.Path
409 # Simply return a path that is contained within LTTNG_HOME; it will
410 # be destroyed when the temporary home goes out of scope.
411 assert self
._lttng
_home
414 prefix
="tmp" if prefix
is None else prefix
,
415 dir=str(self
._lttng
_home
.path
),
419 # Unpack a list of environment variables from a string
420 # such as "HELLO=is_it ME='/you/are/looking/for'"
422 def _unpack_env_vars(env_vars_string
):
423 # type: (str) -> List[Tuple[str, str]]
425 for var
in shlex
.split(env_vars_string
):
426 equal_position
= var
.find("=")
427 # Must have an equal sign and not end with an equal sign
428 if equal_position
== -1 or equal_position
== len(var
) - 1:
430 "Invalid sessiond environment variable: `{}`".format(var
)
433 var_name
= var
[0:equal_position
]
434 var_value
= var
[equal_position
+ 1 :]
436 var_value
= var_value
.replace("'", "")
437 var_value
= var_value
.replace('"', "")
438 unpacked_vars
.append((var_name
, var_value
))
442 def _launch_lttng_sessiond(self
):
443 # type: () -> Optional[subprocess.Popen]
444 is_64bits_host
= sys
.maxsize
> 2**32
447 self
._project
_root
/ "src" / "bin" / "lttng-sessiond" / "lttng-sessiond"
449 consumerd_path_option_name
= "--consumerd{bitness}-path".format(
450 bitness
="64" if is_64bits_host
else "32"
453 self
._project
_root
/ "src" / "bin" / "lttng-consumerd" / "lttng-consumerd"
456 no_sessiond_var
= os
.environ
.get("TEST_NO_SESSIOND")
457 if no_sessiond_var
and no_sessiond_var
== "1":
458 # Run test without a session daemon; the user probably
459 # intends to run one under gdb for example.
462 # Setup the session daemon's environment
463 sessiond_env_vars
= os
.environ
.get("LTTNG_SESSIOND_ENV_VARS")
464 sessiond_env
= os
.environ
.copy()
465 if sessiond_env_vars
:
466 self
._log
("Additional lttng-sessiond environment variables:")
467 additional_vars
= self
._unpack
_env
_vars
(sessiond_env_vars
)
468 for var_name
, var_value
in additional_vars
:
469 self
._log
(" {name}={value}".format(name
=var_name
, value
=var_value
))
470 sessiond_env
[var_name
] = var_value
472 sessiond_env
["LTTNG_SESSION_CONFIG_XSD_PATH"] = str(
473 self
._project
_root
/ "src" / "common"
476 assert self
._lttng
_home
is not None
477 sessiond_env
["LTTNG_HOME"] = str(self
._lttng
_home
.path
)
479 wait_queue
= _SignalWaitQueue()
480 with wait_queue
.intercept_signal(signal
.SIGUSR1
):
482 "Launching session daemon with LTTNG_HOME=`{home_dir}`".format(
483 home_dir
=str(self
._lttng
_home
.path
)
486 process
= subprocess
.Popen(
489 consumerd_path_option_name
,
493 stdout
=subprocess
.PIPE
,
494 stderr
=subprocess
.STDOUT
,
498 if self
._logging
_function
:
499 self
._sessiond
_output
_consumer
= ProcessOutputConsumer(
500 process
, "lttng-sessiond", self
._logging
_function
501 ) # type: Optional[ProcessOutputConsumer]
502 self
._sessiond
_output
_consumer
.daemon
= True
503 self
._sessiond
_output
_consumer
.start()
505 # Wait for SIGUSR1, indicating the sessiond is ready to proceed
506 wait_queue
.wait_for_signal()
510 def _handle_termination_signal(self
, signal_number
, frame
):
511 # type: (int, Optional[FrameType]) -> None
513 "Killed by {signal_name} signal, cleaning-up".format(
514 signal_name
=signal
.strsignal(signal_number
)
519 def launch_wait_trace_test_application(
521 event_count
, # type: int
522 wait_time_between_events_us
=0,
523 wait_before_exit
=False,
524 wait_before_exit_file_path
=None,
526 # type: (int, int, bool, Optional[pathlib.Path]) -> _WaitTraceTestApplication
528 Launch an application that will wait before tracing `event_count` events.
530 return _WaitTraceTestApplication(
539 wait_time_between_events_us
,
541 wait_before_exit_file_path
,
544 def launch_trace_test_constructor_application(self
):
545 # type () -> TraceTestApplication
547 Launch an application that will trace from within constructors.
549 return _TraceTestApplication(
554 / "gen-ust-events-constructor"
555 / "gen-ust-events-constructor",
559 # Clean-up managed processes
562 if self
._sessiond
and self
._sessiond
.poll() is None:
563 # The session daemon is alive; kill it.
565 "Killing session daemon (pid = {sessiond_pid})".format(
566 sessiond_pid
=self
._sessiond
.pid
570 self
._sessiond
.terminate()
571 self
._sessiond
.wait()
572 if self
._sessiond
_output
_consumer
:
573 self
._sessiond
_output
_consumer
.join()
574 self
._sessiond
_output
_consumer
= None
576 self
._log
("Session daemon killed")
577 self
._sessiond
= None
579 self
._lttng
_home
= None
585 @contextlib.contextmanager
586 def test_environment(with_sessiond
, log
=None):
587 # type: (bool, Optional[Callable[[str], None]]) -> Iterator[_Environment]
588 env
= _Environment(with_sessiond
, log
)