Skip to content

Instantly share code, notes, and snippets.

@jraygauthier
Created July 29, 2021 18:39
Show Gist options
  • Save jraygauthier/8f06c917e05ea7886a6ad26ffce70682 to your computer and use it in GitHub Desktop.
Save jraygauthier/8f06c917e05ea7886a6ad26ffce70682 to your computer and use it in GitHub Desktop.
Docker launcher for proper dbus session support in between separate exec calls
#!/usr/bin/env bash
set -euf -o pipefail
declare uid
uid="$(id -u)"
declare tmp_dir="${TMPDIR:-/run/user/${uid}}"
if ! [[ -d "$tmp_dir" ]]; then
# Fallback to unsafe tmp dir (docker case).
tmp_dir="/tmp"
fi
declare dbus_session_address_file="$tmp_dir/current-user-${uid}-dbus-session-address.txt"
declare dbus_session_address
if [[ -f "$dbus_session_address_file" ]]; then
dbus_session_address="$(cat "$dbus_session_address_file")"
else
declare dbus_session_conf_files=( \
"/usr/share/dbus-1/session.conf" \
"/run/current-system/sw/share/dbus-1/session.conf" \
)
declare dbus_session_conf_file
dbus_session_conf_file="$(find "${dbus_session_conf_files[@]}" 2>/dev/null || true | head -n 1)"
if [[ -z "$dbus_session_conf_file" ]] || ! [[ -f "$dbus_session_conf_file" ]]; then
1>&2 printf "ERROR: No 'session.conf' file found at expected locations:"
1>&2 printf " '%q'" "${dbus_session_conf_files[@]}"
1>&2 printf ".\n"
exit 1
fi
declare dbus_daemon_args=( --fork \
--config-file="$dbus_session_conf_file" \
--print-address \
)
1>&2 printf "$ dbus_session_address=\"\$(dbus-daemon"
1>&2 printf " %q" "${dbus_daemon_args[@]}"
1>&2 printf ")\"\n"
dbus_session_address="$(dbus-daemon "${dbus_daemon_args[@]}")"
1>&2 printf "$ echo \"\$dbus_session_address\" > '%s'\n" "$dbus_session_address_file"
echo "$dbus_session_address" > "$dbus_session_address_file"
fi
if [[ -z "$dbus_session_address" ]]; then
1>&2 printf "ERROR: Unexpected empty 'dbus_session_address'.\n"
exit 1
fi
printf "$ export DBUS_SESSION_BUS_ADDRESS=%s\n" "$dbus_session_address"
export "DBUS_SESSION_BUS_ADDRESS=$dbus_session_address"
if [ $# -gt 0 ]; then
exec bash -c "$*"
else
exec bash -i
fi
@jraygauthier
Copy link
Author

See ./docker-dbus-session-launcher.sh for a
nice little launcher that will allow one to exec services and commands depending
on a dbus session from within a docker container.

To be run used as your entry point implementation.

my-docker-entry-point.sh:

./docker-dbus-session-launcher.sh "$@"
# ..

This launche makes sure to:

  1. launch a dbus session daemon it does not already exists, reuse the existing
    daemon otherwise.
  2. export the DBUS_SESSION_BUS_ADDRESS env var.

So, in doing so this dbus session will be reused in between call to docker exec.

This little launcher should work on both nixos, ubuntu based docker containers
and most likely many others. If not, it is easy to adapt.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment