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
_pathlike
(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
_pathlike
(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
_pathlike
(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
_pathlike
(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(self
._compat
_pathlike
(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
_pathlike
(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_pathlike(path
):
213 # type: (pathlib.Path) -> pathlib.Path | str
215 The builtin open() and many methods of the 'os' library in Python >= 3.6
216 expect a path-like object while prior versions expect a string or
217 bytes object. Return the correct type based on the presence of the
218 "__fspath__" attribute specified in PEP-519.
220 if hasattr(path
, "__fspath__"):
226 if not self
._has
_returned
:
227 # This is potentially racy if the pid has been recycled. However,
228 # we can't use pidfd_open since it is only available in python >= 3.9.
233 class WaitTraceTestApplicationGroup
:
236 environment
, # type: Environment
237 application_count
, # type: int
238 event_count
, # type: int
239 wait_time_between_events_us
=0, # type: int
240 wait_before_exit
=False, # type: bool
242 self
._wait
_before
_exit
_file
_path
= (
247 dir=_WaitTraceTestApplication
._compat
_pathlike
(
248 environment
.lttng_home_location
258 for i
in range(application_count
):
259 new_app
= environment
.launch_wait_trace_test_application(
261 wait_time_between_events_us
,
263 self
._wait
_before
_exit
_file
_path
,
266 # Attach an output consumer to log the application's error output (if any).
267 if environment
._logging
_function
:
268 app_output_consumer
= ProcessOutputConsumer(
270 "app-{}".format(str(new_app
.vpid
)),
271 environment
._logging
_function
,
272 ) # type: Optional[ProcessOutputConsumer]
273 app_output_consumer
.daemon
= True
274 app_output_consumer
.start()
275 self
._consumers
.append(app_output_consumer
)
277 self
._apps
.append(new_app
)
281 for app
in self
._apps
:
285 self
, wait_for_apps
=False # type: bool
287 if self
._wait
_before
_exit
_file
_path
is None:
289 "Can't call exit on an application group created with `wait_before_exit=False`"
292 # Wait for apps to have produced all of their events so that we can
293 # cause the death of all apps to happen within a short time span.
294 for app
in self
._apps
:
295 app
.wait_for_tracing_done()
298 _WaitTraceTestApplication
._compat
_pathlike
(
299 self
._wait
_before
_exit
_file
_path
303 # Performed in two passes to allow tests to stress the unregistration of many applications.
304 # Waiting for each app to exit turn-by-turn would defeat the purpose here.
306 for app
in self
._apps
:
310 class _TraceTestApplication
:
312 Create an application that emits events as soon as it is launched. In most
313 scenarios, it is preferable to use a WaitTraceTestApplication.
316 def __init__(self
, binary_path
, environment
):
317 # type: (pathlib.Path, Environment)
318 self
._environment
= environment
# type: Environment
319 self
._has
_returned
= False
321 test_app_env
= os
.environ
.copy()
322 test_app_env
["LTTNG_HOME"] = str(environment
.lttng_home_location
)
323 # Make sure the app is blocked until it is properly registered to
324 # the session daemon.
325 test_app_env
["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
327 test_app_args
= [str(binary_path
)]
329 self
._process
= subprocess
.Popen(
330 test_app_args
, env
=test_app_env
331 ) # type: subprocess.Popen
333 def wait_for_exit(self
):
335 if self
._process
.wait() != 0:
337 "Test application has exit with return code `{return_code}`".format(
338 return_code
=self
._process
.returncode
341 self
._has
_returned
= True
344 if not self
._has
_returned
:
345 # This is potentially racy if the pid has been recycled. However,
346 # we can't use pidfd_open since it is only available in python >= 3.9.
351 class ProcessOutputConsumer(threading
.Thread
, logger
._Logger
):
354 process
, # type: subprocess.Popen
356 log
, # type: Callable[[str], None]
358 threading
.Thread
.__init
__(self
)
360 logger
._Logger
.__init
__(self
, log
)
361 self
._process
= process
365 while self
._process
.poll() is None:
366 assert self
._process
.stdout
367 line
= self
._process
.stdout
.readline().decode("utf-8").replace("\n", "")
369 self
._log
("{prefix}: {line}".format(prefix
=self
._prefix
, line
=line
))
372 # Generate a temporary environment in which to execute a test.
373 class _Environment(logger
._Logger
):
376 with_sessiond
, # type: bool
377 log
=None, # type: Optional[Callable[[str], None]]
378 with_relayd
=False, # type: bool
380 super().__init
__(log
)
381 signal
.signal(signal
.SIGTERM
, self
._handle
_termination
_signal
)
382 signal
.signal(signal
.SIGINT
, self
._handle
_termination
_signal
)
384 # Assumes the project's hierarchy to this file is:
385 # tests/utils/python/this_file
386 self
._project
_root
= (
387 pathlib
.Path(__file__
).absolute().parents
[3]
388 ) # type: pathlib.Path
389 self
._lttng
_home
= TemporaryDirectory(
390 "lttng_test_env_home"
391 ) # type: Optional[TemporaryDirectory]
394 self
._launch
_lttng
_relayd
() if with_relayd
else None
395 ) # type: Optional[subprocess.Popen[bytes]]
396 self
._relayd
_output
_consumer
= None
399 self
._launch
_lttng
_sessiond
() if with_sessiond
else None
400 ) # type: Optional[subprocess.Popen[bytes]]
403 def lttng_home_location(self
):
404 # type: () -> pathlib.Path
405 if self
._lttng
_home
is None:
406 raise RuntimeError("Attempt to access LTTng home after clean-up")
407 return self
._lttng
_home
.path
410 def lttng_client_path(self
):
411 # type: () -> pathlib.Path
412 return self
._project
_root
/ "src" / "bin" / "lttng" / "lttng"
415 def lttng_relayd_control_port(self
):
420 def lttng_relayd_data_port(self
):
425 def lttng_relayd_live_port(self
):
429 def create_temporary_directory(self
, prefix
=None):
430 # type: (Optional[str]) -> pathlib.Path
431 # Simply return a path that is contained within LTTNG_HOME; it will
432 # be destroyed when the temporary home goes out of scope.
433 assert self
._lttng
_home
436 prefix
="tmp" if prefix
is None else prefix
,
437 dir=str(self
._lttng
_home
.path
),
441 # Unpack a list of environment variables from a string
442 # such as "HELLO=is_it ME='/you/are/looking/for'"
444 def _unpack_env_vars(env_vars_string
):
445 # type: (str) -> List[Tuple[str, str]]
447 for var
in shlex
.split(env_vars_string
):
448 equal_position
= var
.find("=")
449 # Must have an equal sign and not end with an equal sign
450 if equal_position
== -1 or equal_position
== len(var
) - 1:
452 "Invalid sessiond environment variable: `{}`".format(var
)
455 var_name
= var
[0:equal_position
]
456 var_value
= var
[equal_position
+ 1 :]
458 var_value
= var_value
.replace("'", "")
459 var_value
= var_value
.replace('"', "")
460 unpacked_vars
.append((var_name
, var_value
))
464 def _launch_lttng_relayd(self
):
465 # type: () -> Optional[subprocess.Popen]
467 self
._project
_root
/ "src" / "bin" / "lttng-relayd" / "lttng-relayd"
469 if os
.environ
.get("LTTNG_TEST_NO_RELAYD", "0") == "1":
470 # Run without a relay daemon; the user may be running one
471 # under gdb, for example.
474 relayd_env_vars
= os
.environ
.get("LTTNG_RELAYD_ENV_VARS")
475 relayd_env
= os
.environ
.copy()
477 self
._log
("Additional lttng-relayd environment variables:")
478 for name
, value
in self
._unpack
_env
_vars
(relayd_env_vars
):
479 self
._log
("{}={}".format(name
, value
))
480 relayd_env
[name
] = value
482 assert self
._lttng
_home
is not None
483 relayd_env
["LTTNG_HOME"] = str(self
._lttng
_home
.path
)
485 "Launching relayd with LTTNG_HOME='${}'".format(str(self
._lttng
_home
.path
))
487 process
= subprocess
.Popen(
491 "tcp://0.0.0.0:{}".format(self
.lttng_relayd_control_port
),
493 "tcp://0.0.0.0:{}".format(self
.lttng_relayd_data_port
),
495 "tcp://localhost:{}".format(self
.lttng_relayd_live_port
),
497 stdout
=subprocess
.PIPE
,
498 stderr
=subprocess
.STDOUT
,
502 if self
._logging
_function
:
503 self
._relayd
_output
_consumer
= ProcessOutputConsumer(
504 process
, "lttng-relayd", self
._logging
_function
506 self
._relayd
_output
_consumer
.daemon
= True
507 self
._relayd
_output
_consumer
.start()
511 def _launch_lttng_sessiond(self
):
512 # type: () -> Optional[subprocess.Popen]
513 is_64bits_host
= sys
.maxsize
> 2**32
516 self
._project
_root
/ "src" / "bin" / "lttng-sessiond" / "lttng-sessiond"
518 consumerd_path_option_name
= "--consumerd{bitness}-path".format(
519 bitness
="64" if is_64bits_host
else "32"
522 self
._project
_root
/ "src" / "bin" / "lttng-consumerd" / "lttng-consumerd"
525 no_sessiond_var
= os
.environ
.get("TEST_NO_SESSIOND")
526 if no_sessiond_var
and no_sessiond_var
== "1":
527 # Run test without a session daemon; the user probably
528 # intends to run one under gdb for example.
531 # Setup the session daemon's environment
532 sessiond_env_vars
= os
.environ
.get("LTTNG_SESSIOND_ENV_VARS")
533 sessiond_env
= os
.environ
.copy()
534 if sessiond_env_vars
:
535 self
._log
("Additional lttng-sessiond environment variables:")
536 additional_vars
= self
._unpack
_env
_vars
(sessiond_env_vars
)
537 for var_name
, var_value
in additional_vars
:
538 self
._log
(" {name}={value}".format(name
=var_name
, value
=var_value
))
539 sessiond_env
[var_name
] = var_value
541 sessiond_env
["LTTNG_SESSION_CONFIG_XSD_PATH"] = str(
542 self
._project
_root
/ "src" / "common"
545 assert self
._lttng
_home
is not None
546 sessiond_env
["LTTNG_HOME"] = str(self
._lttng
_home
.path
)
548 wait_queue
= _SignalWaitQueue()
549 with wait_queue
.intercept_signal(signal
.SIGUSR1
):
551 "Launching session daemon with LTTNG_HOME=`{home_dir}`".format(
552 home_dir
=str(self
._lttng
_home
.path
)
555 process
= subprocess
.Popen(
558 consumerd_path_option_name
,
562 stdout
=subprocess
.PIPE
,
563 stderr
=subprocess
.STDOUT
,
567 if self
._logging
_function
:
568 self
._sessiond
_output
_consumer
= ProcessOutputConsumer(
569 process
, "lttng-sessiond", self
._logging
_function
570 ) # type: Optional[ProcessOutputConsumer]
571 self
._sessiond
_output
_consumer
.daemon
= True
572 self
._sessiond
_output
_consumer
.start()
574 # Wait for SIGUSR1, indicating the sessiond is ready to proceed
575 wait_queue
.wait_for_signal()
579 def _handle_termination_signal(self
, signal_number
, frame
):
580 # type: (int, Optional[FrameType]) -> None
582 "Killed by {signal_name} signal, cleaning-up".format(
583 signal_name
=signal
.strsignal(signal_number
)
588 def launch_wait_trace_test_application(
590 event_count
, # type: int
591 wait_time_between_events_us
=0,
592 wait_before_exit
=False,
593 wait_before_exit_file_path
=None,
595 # type: (int, int, bool, Optional[pathlib.Path]) -> _WaitTraceTestApplication
597 Launch an application that will wait before tracing `event_count` events.
599 return _WaitTraceTestApplication(
608 wait_time_between_events_us
,
610 wait_before_exit_file_path
,
613 def launch_trace_test_constructor_application(self
):
614 # type () -> TraceTestApplication
616 Launch an application that will trace from within constructors.
618 return _TraceTestApplication(
623 / "gen-ust-events-constructor"
624 / "gen-ust-events-constructor",
628 # Clean-up managed processes
631 if self
._sessiond
and self
._sessiond
.poll() is None:
632 # The session daemon is alive; kill it.
634 "Killing session daemon (pid = {sessiond_pid})".format(
635 sessiond_pid
=self
._sessiond
.pid
639 self
._sessiond
.terminate()
640 self
._sessiond
.wait()
641 if self
._sessiond
_output
_consumer
:
642 self
._sessiond
_output
_consumer
.join()
643 self
._sessiond
_output
_consumer
= None
645 self
._log
("Session daemon killed")
646 self
._sessiond
= None
648 if self
._relayd
and self
._relayd
.poll() is None:
649 self
._relayd
.terminate()
651 if self
._relayd
_output
_consumer
:
652 self
._relayd
_output
_consumer
.join()
653 self
._relayd
_output
_consumer
= None
654 self
._log
("Relayd killed")
657 self
._lttng
_home
= None
663 @contextlib.contextmanager
664 def test_environment(with_sessiond
, log
=None, with_relayd
=False):
665 # type: (bool, Optional[Callable[[str], None]], bool) -> Iterator[_Environment]
666 env
= _Environment(with_sessiond
, log
, with_relayd
)