Skip to content

Commit

Permalink
Print bubblejail messages to stderr
Browse files Browse the repository at this point in the history
This separates them from the program output.

Fix `run --wait` adding extra new line at the end.

Also remove all `__debug__` if branches because some distros
use `-O0` optimization level for Python.
  • Loading branch information
igo95862 committed Jun 9, 2024
1 parent 42e3c4a commit 2bc8d35
Show file tree
Hide file tree
Showing 6 changed files with 45 additions and 44 deletions.
8 changes: 4 additions & 4 deletions src/bubblejail/bubblejail_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from argparse import ArgumentParser
from asyncio import run as async_run
from pathlib import Path
from sys import argv, stderr
from sys import argv, stderr, stdout
from typing import TYPE_CHECKING

from .bubblejail_cli_metadata import BUBBLEJAIL_CMD
Expand Down Expand Up @@ -86,8 +86,8 @@ def run_bjail(
wait_for_response=wait,
)
)
if wait:
print(command_return_text)
if wait and command_return_text is not None:
stdout.write(command_return_text)
else:
extra_bwrap_args: Optional[list[str]]
if debug_bwrap_args is not None:
Expand Down Expand Up @@ -145,7 +145,7 @@ def bjail_list(list_what: str) -> None:
str_iterator = iter_subcommands()

for string in str_iterator:
print(string)
print(string, file=stdout)


def bjail_create(
Expand Down
7 changes: 4 additions & 3 deletions src/bubblejail/bubblejail_directories.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from os import environ
from pathlib import Path
from subprocess import run as subprocess_run
from sys import stderr
from tomllib import load as toml_load
from typing import Any, Dict, Generator, Optional

Expand Down Expand Up @@ -33,7 +34,7 @@ def convert_old_conf_to_new() -> None:
if (instance_directory / FILE_NAME_SERVICES).is_file():
continue

print(f"Converting {instance_directory.stem}")
print(f"Converting {instance_directory.stem}", file=stderr)

old_conf_path = instance_directory / "config.toml"
with open(old_conf_path, mode="rb") as old_conf_file:
Expand Down Expand Up @@ -163,7 +164,7 @@ def create_new_instance(
instance.metadata_creation_profile_name = profile_name

if profile_name is not None and print_import_tips:
print("Import tips: ", profile.import_tips)
print("Import tips: ", profile.import_tips, file=stderr)

return instance

Expand Down Expand Up @@ -294,7 +295,7 @@ def overwrite_desktop_entry_for_profile(
# Update desktop MIME database
# Requires `update-desktop-database` binary
# Arch package desktop-file-utils
print("Updating desktop MIME database")
print("Updating desktop MIME database", file=stderr)
cls.update_mime_database()

@classmethod
Expand Down
32 changes: 14 additions & 18 deletions src/bubblejail/bubblejail_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from pathlib import Path
from signal import SIGCHLD, SIGKILL, SIGTERM
from socket import AF_UNIX, socket
from sys import stderr
from time import sleep as sync_sleep
from typing import TYPE_CHECKING

Expand Down Expand Up @@ -148,8 +149,7 @@ def handle_children() -> None:
if exit_pid == 0:
return

if __debug__:
print("Reaped: ", exit_pid, " Exit code: ", exit_code, flush=True)
print("Reaped: ", exit_pid, " Exit code: ", exit_code, file=stderr)

except ChildProcessError:
...
Expand Down Expand Up @@ -268,11 +268,11 @@ def process_has_child(cls) -> bool:
return False

async def termninator_watcher(self) -> None:
if __debug__:
print(
"self.terminator_look_for_command: ",
repr(self.terminator_look_for_command),
)
print(
"self.terminator_look_for_command: ",
repr(self.terminator_look_for_command),
file=stderr,
)

while True:
try:
Expand All @@ -286,8 +286,7 @@ async def termninator_watcher(self) -> None:
)

if is_time_to_termniate:
if __debug__:
print("No children found. Terminating.")
print("No children found. Terminating.", file=stderr)
create_task(self.stop_async())
return
except CancelledError:
Expand Down Expand Up @@ -328,14 +327,12 @@ async def run_command(

async def client_handler(self, reader: StreamReader, writer: StreamWriter) -> None:

if __debug__:
print("Client connected", flush=True)
print("Client connected", file=stderr)

while True:
line = await reader.readline()
if not line:
if __debug__:
print("Reached end of reader. Returning", flush=True)
print("Reached end of reader. Returning", file=stderr)
writer.close()
await writer.wait_closed()
return
Expand All @@ -357,7 +354,7 @@ async def client_handler(self, reader: StreamReader, writer: StreamWriter) -> No
text=run_stdout,
)
case _:
print("Unknown request")
print("Unknown request", file=stderr)
continue

writer.write(response)
Expand All @@ -368,8 +365,7 @@ async def start_async(self) -> None:
self.client_handler,
sock=self.socket,
)
if __debug__:
print("Started unix server", flush=True)
print("Started unix server", file=stderr)
self.termninator_watcher_task = create_task(self.termninator_watcher())

if self.startup_args:
Expand All @@ -380,7 +376,7 @@ async def start_async(self) -> None:
async def stop_async(self) -> None:
self.terminated.set()

print("Terminated", flush=True)
print("Terminated", file=stderr)

async def __aenter__(self) -> None: ...

Expand Down Expand Up @@ -463,7 +459,7 @@ async def run_helper() -> None:
try:
event_loop.run_until_complete(run_helper_task)
except CancelledError:
print("Termninated by CancelledError")
print("Termninated by CancelledError", file=stderr)
finally:
event_loop.close()

Expand Down
25 changes: 13 additions & 12 deletions src/bubblejail/bubblejail_instance.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from functools import cached_property
from os import environ, stat
from pathlib import Path
from sys import stderr
from tempfile import TemporaryDirectory
from tomllib import loads as toml_loads
from typing import Any, cast
Expand Down Expand Up @@ -212,29 +213,29 @@ async def async_run_init(

if dry_run:
runner.genetate_args()
print("Bwrap options:")
print(" ".join(runner.bwrap_options_args))
print("Bwrap options:", file=stderr)
print(" ".join(runner.bwrap_options_args), file=stderr)

print("Helper options:")
print(" ".join(runner.helper_arguments()))
print("Helper options:", file=stderr)
print(" ".join(runner.helper_arguments()), file=stderr)

print("Run args:")
print(" ".join(args_to_run))
print("Run args:", file=stderr)
print(" ".join(args_to_run), file=stderr)

print("D-Bus session args:")
print(" ".join(runner.dbus_proxy_args))
print("D-Bus session args:", file=stderr)
print(" ".join(runner.dbus_proxy_args), file=stderr)
return

async with AsyncExitStack() as exit_stack:
bwrap_process = await runner.setup_runtime(exit_stack, args_to_run)
print(f"Bubblewrap started. PID: {repr(bwrap_process)}")
print(f"Bubblewrap started. PID: {repr(bwrap_process)}", file=stderr)

task_bwrap_main = bwrap_process.wait()

try:
await task_bwrap_main
except CancelledError:
print("Bwrap cancelled")
print("Bwrap cancelled", file=stderr)

if bwrap_process.returncode != 0:
raise BubblewrapRunError(
Expand All @@ -245,7 +246,7 @@ async def async_run_init(
)
)

print("Bubblewrap terminated")
print("Bubblewrap terminated", file=stderr)

async def edit_config_in_editor(self) -> None:
# Create temporary directory
Expand All @@ -263,7 +264,7 @@ async def edit_config_in_editor(self) -> None:

# If file was not modified do nothing
if initial_modification_time >= stat(temp_file_path).st_mtime:
print("File not modified. Not overwriting config")
print("File not modified. Not overwriting config", file=stderr)
return

# Verify that the new config is valid and save to variable
Expand Down
10 changes: 5 additions & 5 deletions src/bubblejail/bubblejail_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from os import O_CLOEXEC, O_NONBLOCK, environ, kill, pipe2
from signal import SIGTERM
from socket import AF_UNIX, socket
from sys import stderr
from tempfile import TemporaryFile
from traceback import print_exc
from typing import TYPE_CHECKING
Expand Down Expand Up @@ -302,8 +303,7 @@ def get_args_file_descriptor(self) -> int:

async def _run_post_init_hooks(self) -> None:
sandboxed_pid = await self.sandboxed_pid
if __debug__:
print(f"Sandboxed PID: {sandboxed_pid}")
print(f"Sandboxed PID: {sandboxed_pid}", file=stderr)

for hook in self.post_init_hooks:
await hook(sandboxed_pid)
Expand All @@ -324,8 +324,8 @@ async def _run_post_shutdown_hooks(self) -> None:
try:
await hook()
except Exception:
print("Failed to run post shutdown hook: ", hook)
print_exc()
print("Failed to run post shutdown hook: ", hook, file=stderr)
print_exc(file=stderr)

def sigterm_handler(self) -> None:
try:
Expand All @@ -337,7 +337,7 @@ def sigterm_handler(self) -> None:

pid_to_kill = self.bubblewrap_pid

print("Terminating PID: ", pid_to_kill)
print("Terminating PID: ", pid_to_kill, file=stderr)
kill(pid_to_kill, SIGTERM)
# No need to wait as the bwrap should terminate when helper exits

Expand Down
7 changes: 5 additions & 2 deletions src/bubblejail/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from os import O_CLOEXEC, O_NONBLOCK, environ, getpid, getuid, pipe2, readlink
from pathlib import Path
from shutil import which
from sys import stderr
from typing import TYPE_CHECKING, TypedDict

from xdg import BaseDirectory
Expand Down Expand Up @@ -427,7 +428,7 @@ def iter_bwrap_options(self) -> ServiceGeneratorType:
try:
wayland_display_env = environ["WAYLAND_DISPLAY"]
except KeyError:
print("No wayland display.")
print("wayland: No wayland display.", file=stderr)

for x in XDG_DESKTOP_VARS:
if x in environ:
Expand Down Expand Up @@ -1063,7 +1064,9 @@ def set_namespaces_limits(
if parent_ns.ns_id != UserNamespace.get_current_ns_id():
parent_ns.setns()
else:
print("Already in parent user namespace")
print(
"namespaces_limits: Already in parent user namespace", file=stderr
)

target_namespace.setns()

Expand Down

0 comments on commit 2bc8d35

Please sign in to comment.