From 3968fc201bf6473d72caf5ce2b75d9b39817e885 Mon Sep 17 00:00:00 2001 From: Hans-Christoph Steiner Date: Thu, 28 Nov 2024 15:55:25 +0100 Subject: [PATCH] /run/user/$UID as fallback if XDG_RUNTIME_DIR is not set XDG mentions `/run/user/$UID` as the value for `XDG_RUNTIME_DIR`: https://www.freedesktop.org/software/systemd/man/latest/pam_systemd.html https://serverfault.com/questions/388840/good-default-for-xdg-runtime-di r/727994#727994 Archlinux, Debian, RedHat, Ubuntu, etc all use `/run/user/$UID` because they follow XDG: https://wiki.archlinux.org/title/XDG_Base_Directory Signed-off-by: Hans-Christoph Steiner --- podman/api/path_utils.py | 10 +++++++++- podman/tests/unit/test_path_utils.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 podman/tests/unit/test_path_utils.py diff --git a/podman/api/path_utils.py b/podman/api/path_utils.py index 84f9769e..5b40bd8c 100644 --- a/podman/api/path_utils.py +++ b/podman/api/path_utils.py @@ -7,11 +7,19 @@ def get_runtime_dir() -> str: - """Returns the runtime directory for the current user""" + """Returns the runtime directory for the current user + + The value in XDG_RUNTIME_DIR is preferred, but that is not always set, for + example, on headless servers. /run/user/$UID is defined in the XDG documentation. + + """ try: return os.environ['XDG_RUNTIME_DIR'] except KeyError: user = getpass.getuser() + run_user = f'/run/user/{user}' + if os.path.isdir(run_user): + return run_user fallback = f'/tmp/podmanpy-runtime-dir-fallback-{user}' try: diff --git a/podman/tests/unit/test_path_utils.py b/podman/tests/unit/test_path_utils.py new file mode 100644 index 00000000..29e02443 --- /dev/null +++ b/podman/tests/unit/test_path_utils.py @@ -0,0 +1,28 @@ +import datetime +import os +import unittest +import tempfile +from unittest import mock + +from podman import api + + +class PathUtilsTestCase(unittest.TestCase): + def setUp(self): + self.xdg_runtime_dir = os.getenv('XDG_RUNTIME_DIR') + print('XDG_RUNTIME_DIR', self.xdg_runtime_dir) + + @mock.patch.dict(os.environ, clear=True) + def test_get_runtime_dir_env_var_set(self): + with tempfile.TemporaryDirectory() as tmpdir: + os.environ['XDG_RUNTIME_DIR'] = str(tmpdir) + self.assertEqual(str(tmpdir), api.path_utils.get_runtime_dir()) + + @unittest.skipUnless(os.getenv('XDG_RUNTIME_DIR'), 'XDG_RUNTIME_DIR must be set') + @mock.patch.dict(os.environ, clear=True) + def test_get_runtime_dir_env_var_not_set(self): + self.assertNotEqual(self.xdg_runtime_dir, api.path_utils.get_runtime_dir()) + + +if __name__ == '__main__': + unittest.main()