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
, Optional
, Tuple
, List
25 class TemporaryDirectory
:
26 def __init__(self
, prefix
: str):
27 self
._directory
_path
= tempfile
.mkdtemp(prefix
=prefix
)
30 shutil
.rmtree(self
._directory
_path
, ignore_errors
=True)
33 def path(self
) -> pathlib
.Path
:
34 return pathlib
.Path(self
._directory
_path
)
37 class _SignalWaitQueue
:
39 Utility class useful to wait for a signal before proceeding.
41 Simply register the `signal` method as the handler for the signal you are
42 interested in and call `wait_for_signal` to wait for its reception.
45 signal.signal(signal.SIGWHATEVER, queue.signal)
47 Waiting for the signal:
48 queue.wait_for_signal()
52 self
._queue
: queue
.Queue
= queue
.Queue()
54 def signal(self
, signal_number
, frame
: Optional
[FrameType
]):
55 self
._queue
.put_nowait(signal_number
)
57 def wait_for_signal(self
):
58 self
._queue
.get(block
=True)
61 class WaitTraceTestApplication
:
63 Create an application that waits before tracing. This allows a test to
64 launch an application, get its PID, and get it to start tracing when it
65 has completed its setup.
70 binary_path
: pathlib
.Path
,
72 environment
: "Environment",
73 wait_time_between_events_us
: int = 0,
75 self
._environment
: Environment
= environment
77 # The test application currently produces 5 different events per iteration.
78 raise ValueError("event count must be a multiple of 5")
79 self
._iteration
_count
: int = int(event_count
/ 5)
80 # File that the application will wait to see before tracing its events.
81 self
._app
_start
_tracing
_file
_path
: pathlib
.Path
= pathlib
.Path(
84 suffix
="_start_tracing",
85 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
88 self
._has
_returned
= False
90 test_app_env
= os
.environ
.copy()
91 test_app_env
["LTTNG_HOME"] = str(environment
.lttng_home_location
)
92 # Make sure the app is blocked until it is properly registered to
94 test_app_env
["LTTNG_UST_REGISTER_TIMEOUT"] = "-1"
96 # File that the application will create to indicate it has completed its initialization.
97 app_ready_file_path
: str = tempfile
.mktemp(
100 dir=self
._compat
_open
_path
(environment
.lttng_home_location
),
103 test_app_args
= [str(binary_path
)]
104 test_app_args
.extend(
106 "--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(
107 iteration_count
=self
._iteration
_count
,
108 app_ready_file_path
=app_ready_file_path
,
109 app_start_tracing_file_path
=self
._app
_start
_tracing
_file
_path
,
110 wait_time_between_events_us
=wait_time_between_events_us
,
115 self
._process
: subprocess
.Popen
= subprocess
.Popen(
120 # Wait for the application to create the file indicating it has fully
121 # initialized. Make sure the app hasn't crashed in order to not wait
124 if os
.path
.exists(app_ready_file_path
):
127 if self
._process
.poll() is not None:
128 # Application has unexepectedly returned.
130 "Test application has unexepectedly returned during its initialization with return code `{return_code}`".format(
131 return_code
=self
._process
.returncode
137 def trace(self
) -> None:
138 if self
._process
.poll() is not None:
139 # Application has unexepectedly returned.
141 "Test application has unexepectedly before tracing with return code `{return_code}`".format(
142 return_code
=self
._process
.returncode
145 open(self
._compat
_open
_path
(self
._app
_start
_tracing
_file
_path
), mode
="x")
147 def wait_for_exit(self
) -> None:
148 if self
._process
.wait() != 0:
150 "Test application has exit with return code `{return_code}`".format(
151 return_code
=self
._process
.returncode
154 self
._has
_returned
= True
157 def vpid(self
) -> int:
158 return self
._process
.pid
161 def _compat_open_path(path
):
162 # type: (pathlib.Path)
164 The builtin open() in python >= 3.6 expects a path-like object while
165 prior versions expect a string or bytes object. Return the correct type
166 based on the presence of the "__fspath__" attribute specified in PEP-519.
168 if hasattr(path
, "__fspath__"):
174 if not self
._has
_returned
:
175 # This is potentially racy if the pid has been recycled. However,
176 # we can't use pidfd_open since it is only available in python >= 3.9.
181 class ProcessOutputConsumer(threading
.Thread
, logger
._Logger
):
183 self
, process
: subprocess
.Popen
, name
: str, log
: Callable
[[str], None]
185 threading
.Thread
.__init
__(self
)
187 logger
._Logger
.__init
__(self
, log
)
188 self
._process
= process
190 def run(self
) -> None:
191 while self
._process
.poll() is None:
192 assert self
._process
.stdout
193 line
= self
._process
.stdout
.readline().decode("utf-8").replace("\n", "")
195 self
._log
("{prefix}: {line}".format(prefix
=self
._prefix
, line
=line
))
198 # Generate a temporary environment in which to execute a test.
199 class _Environment(logger
._Logger
):
201 self
, with_sessiond
: bool, log
: Optional
[Callable
[[str], None]] = None
203 super().__init
__(log
)
204 signal
.signal(signal
.SIGTERM
, self
._handle
_termination
_signal
)
205 signal
.signal(signal
.SIGINT
, self
._handle
_termination
_signal
)
207 # Assumes the project's hierarchy to this file is:
208 # tests/utils/python/this_file
209 self
._project
_root
: pathlib
.Path
= pathlib
.Path(__file__
).absolute().parents
[3]
210 self
._lttng
_home
: Optional
[TemporaryDirectory
] = TemporaryDirectory(
211 "lttng_test_env_home"
214 self
._sessiond
: Optional
[subprocess
.Popen
[bytes
]] = (
215 self
._launch
_lttng
_sessiond
() if with_sessiond
else None
219 def lttng_home_location(self
) -> pathlib
.Path
:
220 if self
._lttng
_home
is None:
221 raise RuntimeError("Attempt to access LTTng home after clean-up")
222 return self
._lttng
_home
.path
225 def lttng_client_path(self
) -> pathlib
.Path
:
226 return self
._project
_root
/ "src" / "bin" / "lttng" / "lttng"
228 def create_temporary_directory(self
, prefix
: Optional
[str] = None) -> pathlib
.Path
:
229 # Simply return a path that is contained within LTTNG_HOME; it will
230 # be destroyed when the temporary home goes out of scope.
231 assert self
._lttng
_home
234 prefix
="tmp" if prefix
is None else prefix
,
235 dir=str(self
._lttng
_home
.path
),
239 # Unpack a list of environment variables from a string
240 # such as "HELLO=is_it ME='/you/are/looking/for'"
242 def _unpack_env_vars(env_vars_string
: str) -> List
[Tuple
[str, str]]:
244 for var
in shlex
.split(env_vars_string
):
245 equal_position
= var
.find("=")
246 # Must have an equal sign and not end with an equal sign
247 if equal_position
== -1 or equal_position
== len(var
) - 1:
249 "Invalid sessiond environment variable: `{}`".format(var
)
252 var_name
= var
[0:equal_position
]
253 var_value
= var
[equal_position
+ 1 :]
255 var_value
= var_value
.replace("'", "")
256 var_value
= var_value
.replace('"', "")
257 unpacked_vars
.append((var_name
, var_value
))
261 def _launch_lttng_sessiond(self
) -> Optional
[subprocess
.Popen
]:
262 is_64bits_host
= sys
.maxsize
> 2**32
265 self
._project
_root
/ "src" / "bin" / "lttng-sessiond" / "lttng-sessiond"
267 consumerd_path_option_name
= "--consumerd{bitness}-path".format(
268 bitness
="64" if is_64bits_host
else "32"
271 self
._project
_root
/ "src" / "bin" / "lttng-consumerd" / "lttng-consumerd"
274 no_sessiond_var
= os
.environ
.get("TEST_NO_SESSIOND")
275 if no_sessiond_var
and no_sessiond_var
== "1":
276 # Run test without a session daemon; the user probably
277 # intends to run one under gdb for example.
280 # Setup the session daemon's environment
281 sessiond_env_vars
= os
.environ
.get("LTTNG_SESSIOND_ENV_VARS")
282 sessiond_env
= os
.environ
.copy()
283 if sessiond_env_vars
:
284 self
._log
("Additional lttng-sessiond environment variables:")
285 additional_vars
= self
._unpack
_env
_vars
(sessiond_env_vars
)
286 for var_name
, var_value
in additional_vars
:
287 self
._log
(" {name}={value}".format(name
=var_name
, value
=var_value
))
288 sessiond_env
[var_name
] = var_value
290 sessiond_env
["LTTNG_SESSION_CONFIG_XSD_PATH"] = str(
291 self
._project
_root
/ "src" / "common"
294 assert self
._lttng
_home
is not None
295 sessiond_env
["LTTNG_HOME"] = str(self
._lttng
_home
.path
)
297 wait_queue
= _SignalWaitQueue()
298 signal
.signal(signal
.SIGUSR1
, wait_queue
.signal
)
301 "Launching session daemon with LTTNG_HOME=`{home_dir}`".format(
302 home_dir
=str(self
._lttng
_home
.path
)
305 process
= subprocess
.Popen(
308 consumerd_path_option_name
,
312 stdout
=subprocess
.PIPE
,
313 stderr
=subprocess
.STDOUT
,
317 if self
._logging
_function
:
318 self
._sessiond
_output
_consumer
: Optional
[
319 ProcessOutputConsumer
320 ] = ProcessOutputConsumer(process
, "lttng-sessiond", self
._logging
_function
)
321 self
._sessiond
_output
_consumer
.daemon
= True
322 self
._sessiond
_output
_consumer
.start()
324 # Wait for SIGUSR1, indicating the sessiond is ready to proceed
325 wait_queue
.wait_for_signal()
326 signal
.signal(signal
.SIGUSR1
, wait_queue
.signal
)
330 def _handle_termination_signal(
331 self
, signal_number
: int, frame
: Optional
[FrameType
]
334 "Killed by {signal_name} signal, cleaning-up".format(
335 signal_name
=signal
.strsignal(signal_number
)
340 def launch_wait_trace_test_application(
341 self
, event_count
: int
342 ) -> WaitTraceTestApplication
:
344 Launch an application that will wait before tracing `event_count` events.
346 return WaitTraceTestApplication(
357 # Clean-up managed processes
358 def _cleanup(self
) -> None:
359 if self
._sessiond
and self
._sessiond
.poll() is None:
360 # The session daemon is alive; kill it.
362 "Killing session daemon (pid = {sessiond_pid})".format(
363 sessiond_pid
=self
._sessiond
.pid
367 self
._sessiond
.terminate()
368 self
._sessiond
.wait()
369 if self
._sessiond
_output
_consumer
:
370 self
._sessiond
_output
_consumer
.join()
371 self
._sessiond
_output
_consumer
= None
373 self
._log
("Session daemon killed")
374 self
._sessiond
= None
376 self
._lttng
_home
= None
382 @contextlib.contextmanager
383 def test_environment(with_sessiond
: bool, log
: Optional
[Callable
[[str], None]] = None):
384 env
= _Environment(with_sessiond
, log
)