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
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)
67 class WaitTraceTestApplication
:
69 Create an application that waits before tracing. This allows a test to
70 launch an application, get its PID, and get it to start tracing when it
71 has completed its setup.
76 binary_path
, # type: pathlib.Path
77 event_count
, # type: int
78 environment
, # type: Environment
79 wait_time_between_events_us
=0, # type: int
81 self
._environment
= environment
# type: Environment
83 # The test application currently produces 5 different events per iteration.
84 raise ValueError("event count must be a multiple of 5")
85 self
._iteration
_count
= int(event_count
/ 5) # type: int
86 # File that the application will wait to see before tracing its events.
87 self
._app
_start
_tracing
_file
_path
= pathlib
.Path(
90 suffix
="_start_tracing",
91 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
94 self
._has
_returned
= False
96 test_app_env
= os
.environ
.copy()
97 test_app_env
["LTTNG_HOME"] = str(environment
.lttng_home_location
)
98 # Make sure the app is blocked until it is properly registered to
100 test_app_env
["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
102 # File that the application will create to indicate it has completed its initialization.
103 app_ready_file_path
= tempfile
.mktemp(
106 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
109 test_app_args
= [str(binary_path
)]
110 test_app_args
.extend(
112 "--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(
113 iteration_count
=self
._iteration
_count
,
114 app_ready_file_path
=app_ready_file_path
,
115 app_start_tracing_file_path
=self
._app
_start
_tracing
_file
_path
,
116 wait_time_between_events_us
=wait_time_between_events_us
,
121 self
._process
= subprocess
.Popen(
124 ) # type: subprocess.Popen
126 # Wait for the application to create the file indicating it has fully
127 # initialized. Make sure the app hasn't crashed in order to not wait
130 if os
.path
.exists(app_ready_file_path
):
133 if self
._process
.poll() is not None:
134 # Application has unexepectedly returned.
136 "Test application has unexepectedly returned during its initialization with return code `{return_code}`".format(
137 return_code
=self
._process
.returncode
145 if self
._process
.poll() is not None:
146 # Application has unexepectedly returned.
148 "Test application has unexepectedly before tracing with return code `{return_code}`".format(
149 return_code
=self
._process
.returncode
152 open(self
._compat
_open
_path
(self
._app
_start
_tracing
_file
_path
), mode
="x")
154 def wait_for_exit(self
):
156 if self
._process
.wait() != 0:
158 "Test application has exit with return code `{return_code}`".format(
159 return_code
=self
._process
.returncode
162 self
._has
_returned
= True
167 return self
._process
.pid
170 def _compat_open_path(path
):
171 # type: (pathlib.Path) -> pathlib.Path | str
173 The builtin open() in python >= 3.6 expects a path-like object while
174 prior versions expect a string or bytes object. Return the correct type
175 based on the presence of the "__fspath__" attribute specified in PEP-519.
177 if hasattr(path
, "__fspath__"):
183 if not self
._has
_returned
:
184 # This is potentially racy if the pid has been recycled. However,
185 # we can't use pidfd_open since it is only available in python >= 3.9.
190 class TraceTestApplication
:
192 Create an application to trace.
195 def __init__(self
, binary_path
: pathlib
.Path
, environment
: "Environment"):
196 self
._environment
: Environment
= environment
197 self
._has
_returned
= False
199 test_app_env
= os
.environ
.copy()
200 test_app_env
["LTTNG_HOME"] = str(environment
.lttng_home_location
)
201 # Make sure the app is blocked until it is properly registered to
202 # the session daemon.
203 test_app_env
["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
205 test_app_args
= [str(binary_path
)]
207 self
._process
: subprocess
.Popen
= subprocess
.Popen(
208 test_app_args
, env
=test_app_env
211 def wait_for_exit(self
) -> None:
212 if self
._process
.wait() != 0:
214 "Test application has exit with return code `{return_code}`".format(
215 return_code
=self
._process
.returncode
218 self
._has
_returned
= True
221 if not self
._has
_returned
:
222 # This is potentially racy if the pid has been recycled. However,
223 # we can't use pidfd_open since it is only available in python >= 3.9.
228 class ProcessOutputConsumer(threading
.Thread
, logger
._Logger
):
231 process
, # type: subprocess.Popen
233 log
, # type: Callable[[str], None]
235 threading
.Thread
.__init
__(self
)
237 logger
._Logger
.__init
__(self
, log
)
238 self
._process
= process
242 while self
._process
.poll() is None:
243 assert self
._process
.stdout
244 line
= self
._process
.stdout
.readline().decode("utf-8").replace("\n", "")
246 self
._log
("{prefix}: {line}".format(prefix
=self
._prefix
, line
=line
))
249 # Generate a temporary environment in which to execute a test.
250 class _Environment(logger
._Logger
):
253 with_sessiond
, # type: bool
254 log
=None, # type: Optional[Callable[[str], None]]
256 super().__init
__(log
)
257 signal
.signal(signal
.SIGTERM
, self
._handle
_termination
_signal
)
258 signal
.signal(signal
.SIGINT
, self
._handle
_termination
_signal
)
260 # Assumes the project's hierarchy to this file is:
261 # tests/utils/python/this_file
262 self
._project
_root
= (
263 pathlib
.Path(__file__
).absolute().parents
[3]
264 ) # type: pathlib.Path
265 self
._lttng
_home
= TemporaryDirectory(
266 "lttng_test_env_home"
267 ) # type: Optional[TemporaryDirectory]
270 self
._launch
_lttng
_sessiond
() if with_sessiond
else None
271 ) # type: Optional[subprocess.Popen[bytes]]
274 def lttng_home_location(self
):
275 # type: () -> pathlib.Path
276 if self
._lttng
_home
is None:
277 raise RuntimeError("Attempt to access LTTng home after clean-up")
278 return self
._lttng
_home
.path
281 def lttng_client_path(self
):
282 # type: () -> pathlib.Path
283 return self
._project
_root
/ "src" / "bin" / "lttng" / "lttng"
285 def create_temporary_directory(self
, prefix
=None):
286 # type: (Optional[str]) -> pathlib.Path
287 # Simply return a path that is contained within LTTNG_HOME; it will
288 # be destroyed when the temporary home goes out of scope.
289 assert self
._lttng
_home
292 prefix
="tmp" if prefix
is None else prefix
,
293 dir=str(self
._lttng
_home
.path
),
297 # Unpack a list of environment variables from a string
298 # such as "HELLO=is_it ME='/you/are/looking/for'"
300 def _unpack_env_vars(env_vars_string
):
301 # type: (str) -> List[Tuple[str, str]]
303 for var
in shlex
.split(env_vars_string
):
304 equal_position
= var
.find("=")
305 # Must have an equal sign and not end with an equal sign
306 if equal_position
== -1 or equal_position
== len(var
) - 1:
308 "Invalid sessiond environment variable: `{}`".format(var
)
311 var_name
= var
[0:equal_position
]
312 var_value
= var
[equal_position
+ 1 :]
314 var_value
= var_value
.replace("'", "")
315 var_value
= var_value
.replace('"', "")
316 unpacked_vars
.append((var_name
, var_value
))
320 def _launch_lttng_sessiond(self
):
321 # type: () -> Optional[subprocess.Popen]
322 is_64bits_host
= sys
.maxsize
> 2**32
325 self
._project
_root
/ "src" / "bin" / "lttng-sessiond" / "lttng-sessiond"
327 consumerd_path_option_name
= "--consumerd{bitness}-path".format(
328 bitness
="64" if is_64bits_host
else "32"
331 self
._project
_root
/ "src" / "bin" / "lttng-consumerd" / "lttng-consumerd"
334 no_sessiond_var
= os
.environ
.get("TEST_NO_SESSIOND")
335 if no_sessiond_var
and no_sessiond_var
== "1":
336 # Run test without a session daemon; the user probably
337 # intends to run one under gdb for example.
340 # Setup the session daemon's environment
341 sessiond_env_vars
= os
.environ
.get("LTTNG_SESSIOND_ENV_VARS")
342 sessiond_env
= os
.environ
.copy()
343 if sessiond_env_vars
:
344 self
._log
("Additional lttng-sessiond environment variables:")
345 additional_vars
= self
._unpack
_env
_vars
(sessiond_env_vars
)
346 for var_name
, var_value
in additional_vars
:
347 self
._log
(" {name}={value}".format(name
=var_name
, value
=var_value
))
348 sessiond_env
[var_name
] = var_value
350 sessiond_env
["LTTNG_SESSION_CONFIG_XSD_PATH"] = str(
351 self
._project
_root
/ "src" / "common"
354 assert self
._lttng
_home
is not None
355 sessiond_env
["LTTNG_HOME"] = str(self
._lttng
_home
.path
)
357 wait_queue
= _SignalWaitQueue()
358 signal
.signal(signal
.SIGUSR1
, wait_queue
.signal
)
361 "Launching session daemon with LTTNG_HOME=`{home_dir}`".format(
362 home_dir
=str(self
._lttng
_home
.path
)
365 process
= subprocess
.Popen(
368 consumerd_path_option_name
,
372 stdout
=subprocess
.PIPE
,
373 stderr
=subprocess
.STDOUT
,
377 if self
._logging
_function
:
378 self
._sessiond
_output
_consumer
= ProcessOutputConsumer(
379 process
, "lttng-sessiond", self
._logging
_function
380 ) # type: Optional[ProcessOutputConsumer]
381 self
._sessiond
_output
_consumer
.daemon
= True
382 self
._sessiond
_output
_consumer
.start()
384 # Wait for SIGUSR1, indicating the sessiond is ready to proceed
385 wait_queue
.wait_for_signal()
386 signal
.signal(signal
.SIGUSR1
, wait_queue
.signal
)
390 def _handle_termination_signal(self
, signal_number
, frame
):
391 # type: (int, Optional[FrameType]) -> None
393 "Killed by {signal_name} signal, cleaning-up".format(
394 signal_name
=signal
.strsignal(signal_number
)
399 def launch_wait_trace_test_application(self
, event_count
):
400 # type: (int) -> WaitTraceTestApplication
402 Launch an application that will wait before tracing `event_count` events.
404 return WaitTraceTestApplication(
415 def launch_trace_test_constructor_application(
417 ) -> TraceTestApplication
:
419 Launch an application that will trace from within constructors.
421 return TraceTestApplication(
426 / "gen-ust-events-constructor"
427 / "gen-ust-events-constructor",
431 # Clean-up managed processes
434 if self
._sessiond
and self
._sessiond
.poll() is None:
435 # The session daemon is alive; kill it.
437 "Killing session daemon (pid = {sessiond_pid})".format(
438 sessiond_pid
=self
._sessiond
.pid
442 self
._sessiond
.terminate()
443 self
._sessiond
.wait()
444 if self
._sessiond
_output
_consumer
:
445 self
._sessiond
_output
_consumer
.join()
446 self
._sessiond
_output
_consumer
= None
448 self
._log
("Session daemon killed")
449 self
._sessiond
= None
451 self
._lttng
_home
= None
457 @contextlib.contextmanager
458 def test_environment(with_sessiond
, log
=None):
459 # type: (bool, Optional[Callable[[str], None]]) -> Iterator[_Environment]
460 env
= _Environment(with_sessiond
, log
)