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
95 self
._iteration
_count
= event_count
96 # File that the application will wait to see before tracing its events.
97 self
._app
_start
_tracing
_file
_path
= pathlib
.Path(
100 suffix
="_start_tracing",
101 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
104 self
._has
_returned
= False
106 test_app_env
= os
.environ
.copy()
107 test_app_env
["LTTNG_HOME"] = str(environment
.lttng_home_location
)
108 # Make sure the app is blocked until it is properly registered to
109 # the session daemon.
110 test_app_env
["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
112 # File that the application will create to indicate it has completed its initialization.
113 app_ready_file_path
= tempfile
.mktemp(
116 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
119 test_app_args
= [str(binary_path
)]
120 test_app_args
.extend(
122 "--iter {iteration_count} --sync-application-in-main-touch {app_ready_file_path} --sync-before-first-event {app_start_tracing_file_path} --wait {wait_time_between_events_us}".format(
123 iteration_count
=self
._iteration
_count
,
124 app_ready_file_path
=app_ready_file_path
,
125 app_start_tracing_file_path
=self
._app
_start
_tracing
_file
_path
,
126 wait_time_between_events_us
=wait_time_between_events_us
,
131 self
._process
= subprocess
.Popen(
134 ) # type: subprocess.Popen
136 # Wait for the application to create the file indicating it has fully
137 # initialized. Make sure the app hasn't crashed in order to not wait
140 if os
.path
.exists(app_ready_file_path
):
143 if self
._process
.poll() is not None:
144 # Application has unexepectedly returned.
146 "Test application has unexepectedly returned during its initialization with return code `{return_code}`".format(
147 return_code
=self
._process
.returncode
155 if self
._process
.poll() is not None:
156 # Application has unexepectedly returned.
158 "Test application has unexepectedly before tracing with return code `{return_code}`".format(
159 return_code
=self
._process
.returncode
162 open(self
._compat
_open
_path
(self
._app
_start
_tracing
_file
_path
), mode
="x")
164 def wait_for_exit(self
):
166 if self
._process
.wait() != 0:
168 "Test application has exit with return code `{return_code}`".format(
169 return_code
=self
._process
.returncode
172 self
._has
_returned
= True
177 return self
._process
.pid
180 def _compat_open_path(path
):
181 # type: (pathlib.Path) -> pathlib.Path | str
183 The builtin open() in python >= 3.6 expects a path-like object while
184 prior versions expect a string or bytes object. Return the correct type
185 based on the presence of the "__fspath__" attribute specified in PEP-519.
187 if hasattr(path
, "__fspath__"):
193 if not self
._has
_returned
:
194 # This is potentially racy if the pid has been recycled. However,
195 # we can't use pidfd_open since it is only available in python >= 3.9.
200 class TraceTestApplication
:
202 Create an application that emits events as soon as it is launched. In most
203 scenarios, it is preferable to use a WaitTraceTestApplication.
206 def __init__(self
, binary_path
, environment
):
207 # type: (pathlib.Path, Environment)
208 self
._environment
= environment
# type: Environment
209 self
._has
_returned
= False
211 test_app_env
= os
.environ
.copy()
212 test_app_env
["LTTNG_HOME"] = str(environment
.lttng_home_location
)
213 # Make sure the app is blocked until it is properly registered to
214 # the session daemon.
215 test_app_env
["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
217 test_app_args
= [str(binary_path
)]
219 self
._process
= subprocess
.Popen(
220 test_app_args
, env
=test_app_env
221 ) # type: subprocess.Popen
223 def wait_for_exit(self
):
225 if self
._process
.wait() != 0:
227 "Test application has exit with return code `{return_code}`".format(
228 return_code
=self
._process
.returncode
231 self
._has
_returned
= True
234 if not self
._has
_returned
:
235 # This is potentially racy if the pid has been recycled. However,
236 # we can't use pidfd_open since it is only available in python >= 3.9.
241 class ProcessOutputConsumer(threading
.Thread
, logger
._Logger
):
244 process
, # type: subprocess.Popen
246 log
, # type: Callable[[str], None]
248 threading
.Thread
.__init
__(self
)
250 logger
._Logger
.__init
__(self
, log
)
251 self
._process
= process
255 while self
._process
.poll() is None:
256 assert self
._process
.stdout
257 line
= self
._process
.stdout
.readline().decode("utf-8").replace("\n", "")
259 self
._log
("{prefix}: {line}".format(prefix
=self
._prefix
, line
=line
))
262 # Generate a temporary environment in which to execute a test.
263 class _Environment(logger
._Logger
):
266 with_sessiond
, # type: bool
267 log
=None, # type: Optional[Callable[[str], None]]
269 super().__init
__(log
)
270 signal
.signal(signal
.SIGTERM
, self
._handle
_termination
_signal
)
271 signal
.signal(signal
.SIGINT
, self
._handle
_termination
_signal
)
273 # Assumes the project's hierarchy to this file is:
274 # tests/utils/python/this_file
275 self
._project
_root
= (
276 pathlib
.Path(__file__
).absolute().parents
[3]
277 ) # type: pathlib.Path
278 self
._lttng
_home
= TemporaryDirectory(
279 "lttng_test_env_home"
280 ) # type: Optional[TemporaryDirectory]
283 self
._launch
_lttng
_sessiond
() if with_sessiond
else None
284 ) # type: Optional[subprocess.Popen[bytes]]
287 def lttng_home_location(self
):
288 # type: () -> pathlib.Path
289 if self
._lttng
_home
is None:
290 raise RuntimeError("Attempt to access LTTng home after clean-up")
291 return self
._lttng
_home
.path
294 def lttng_client_path(self
):
295 # type: () -> pathlib.Path
296 return self
._project
_root
/ "src" / "bin" / "lttng" / "lttng"
298 def create_temporary_directory(self
, prefix
=None):
299 # type: (Optional[str]) -> pathlib.Path
300 # Simply return a path that is contained within LTTNG_HOME; it will
301 # be destroyed when the temporary home goes out of scope.
302 assert self
._lttng
_home
305 prefix
="tmp" if prefix
is None else prefix
,
306 dir=str(self
._lttng
_home
.path
),
310 # Unpack a list of environment variables from a string
311 # such as "HELLO=is_it ME='/you/are/looking/for'"
313 def _unpack_env_vars(env_vars_string
):
314 # type: (str) -> List[Tuple[str, str]]
316 for var
in shlex
.split(env_vars_string
):
317 equal_position
= var
.find("=")
318 # Must have an equal sign and not end with an equal sign
319 if equal_position
== -1 or equal_position
== len(var
) - 1:
321 "Invalid sessiond environment variable: `{}`".format(var
)
324 var_name
= var
[0:equal_position
]
325 var_value
= var
[equal_position
+ 1 :]
327 var_value
= var_value
.replace("'", "")
328 var_value
= var_value
.replace('"', "")
329 unpacked_vars
.append((var_name
, var_value
))
333 def _launch_lttng_sessiond(self
):
334 # type: () -> Optional[subprocess.Popen]
335 is_64bits_host
= sys
.maxsize
> 2**32
338 self
._project
_root
/ "src" / "bin" / "lttng-sessiond" / "lttng-sessiond"
340 consumerd_path_option_name
= "--consumerd{bitness}-path".format(
341 bitness
="64" if is_64bits_host
else "32"
344 self
._project
_root
/ "src" / "bin" / "lttng-consumerd" / "lttng-consumerd"
347 no_sessiond_var
= os
.environ
.get("TEST_NO_SESSIOND")
348 if no_sessiond_var
and no_sessiond_var
== "1":
349 # Run test without a session daemon; the user probably
350 # intends to run one under gdb for example.
353 # Setup the session daemon's environment
354 sessiond_env_vars
= os
.environ
.get("LTTNG_SESSIOND_ENV_VARS")
355 sessiond_env
= os
.environ
.copy()
356 if sessiond_env_vars
:
357 self
._log
("Additional lttng-sessiond environment variables:")
358 additional_vars
= self
._unpack
_env
_vars
(sessiond_env_vars
)
359 for var_name
, var_value
in additional_vars
:
360 self
._log
(" {name}={value}".format(name
=var_name
, value
=var_value
))
361 sessiond_env
[var_name
] = var_value
363 sessiond_env
["LTTNG_SESSION_CONFIG_XSD_PATH"] = str(
364 self
._project
_root
/ "src" / "common"
367 assert self
._lttng
_home
is not None
368 sessiond_env
["LTTNG_HOME"] = str(self
._lttng
_home
.path
)
370 wait_queue
= _SignalWaitQueue()
371 with wait_queue
.intercept_signal(signal
.SIGUSR1
):
373 "Launching session daemon with LTTNG_HOME=`{home_dir}`".format(
374 home_dir
=str(self
._lttng
_home
.path
)
377 process
= subprocess
.Popen(
380 consumerd_path_option_name
,
384 stdout
=subprocess
.PIPE
,
385 stderr
=subprocess
.STDOUT
,
389 if self
._logging
_function
:
390 self
._sessiond
_output
_consumer
= ProcessOutputConsumer(
391 process
, "lttng-sessiond", self
._logging
_function
392 ) # type: Optional[ProcessOutputConsumer]
393 self
._sessiond
_output
_consumer
.daemon
= True
394 self
._sessiond
_output
_consumer
.start()
396 # Wait for SIGUSR1, indicating the sessiond is ready to proceed
397 wait_queue
.wait_for_signal()
401 def _handle_termination_signal(self
, signal_number
, frame
):
402 # type: (int, Optional[FrameType]) -> None
404 "Killed by {signal_name} signal, cleaning-up".format(
405 signal_name
=signal
.strsignal(signal_number
)
410 def launch_wait_trace_test_application(self
, event_count
):
411 # type: (int) -> WaitTraceTestApplication
413 Launch an application that will wait before tracing `event_count` events.
415 return WaitTraceTestApplication(
426 def launch_trace_test_constructor_application(self
):
427 # type () -> TraceTestApplication
429 Launch an application that will trace from within constructors.
431 return TraceTestApplication(
436 / "gen-ust-events-constructor"
437 / "gen-ust-events-constructor",
441 # Clean-up managed processes
444 if self
._sessiond
and self
._sessiond
.poll() is None:
445 # The session daemon is alive; kill it.
447 "Killing session daemon (pid = {sessiond_pid})".format(
448 sessiond_pid
=self
._sessiond
.pid
452 self
._sessiond
.terminate()
453 self
._sessiond
.wait()
454 if self
._sessiond
_output
_consumer
:
455 self
._sessiond
_output
_consumer
.join()
456 self
._sessiond
_output
_consumer
= None
458 self
._log
("Session daemon killed")
459 self
._sessiond
= None
461 self
._lttng
_home
= None
467 @contextlib.contextmanager
468 def test_environment(with_sessiond
, log
=None):
469 # type: (bool, Optional[Callable[[str], None]]) -> Iterator[_Environment]
470 env
= _Environment(with_sessiond
, log
)