Skip to content

Commit

Permalink
feat: use systemd-run, fix topgrade (#130)
Browse files Browse the repository at this point in the history
  • Loading branch information
gerblesh authored Sep 5, 2024
1 parent dce31e5 commit e13e6ce
Show file tree
Hide file tree
Showing 5 changed files with 199 additions and 164 deletions.
166 changes: 163 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,165 @@
/output
/dist
*.egg-info
*.**.pyc
*.pyc

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock

# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock

# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
.pdm.toml
.pdm-python
.pdm-build/

# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/

# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
40 changes: 15 additions & 25 deletions src/ublue_update/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from ublue_update.update_inhibitors.hardware import check_hardware_inhibitors
from ublue_update.update_inhibitors.custom import check_custom_inhibitors
from ublue_update.config import cfg
from ublue_update.session import get_xdg_runtime_dir, get_active_sessions
from ublue_update.session import get_active_sessions
from ublue_update.filelock import acquire_lock, release_lock


Expand All @@ -37,17 +37,12 @@ def notify(title: str, body: str, actions: list = [], urgency: str = "normal"):
except KeyError as e:
log.error("failed to get active logind session info", e)
for user in users:
try:
xdg_runtime_dir = get_xdg_runtime_dir(user["User"])
except KeyError as e:
log.error(f"failed to get xdg_runtime_dir for user: {user['Name']}", e)
return
user_args = [
"/usr/bin/sudo",
"-u",
f"{user['Name']}",
"DISPLAY=:0",
f"DBUS_SESSION_BUS_ADDRESS=unix:path={xdg_runtime_dir}/bus",
"/usr/bin/systemd-run",
"--user",
"--machine",
f"{user['user']}@",
"--wait",
]
user_args += args
out = subprocess.run(user_args, capture_output=True)
Expand Down Expand Up @@ -119,6 +114,8 @@ def run_updates(system, system_update_available):
users = []

"""System"""
# remove backwards compat warnings in topgrade (requires user confirmation without this env var)
os.environ["TOPGRADE_SKIP_BRKC_NOTIFY"] = "true"
out = subprocess.run(
[
"/usr/bin/topgrade",
Expand All @@ -136,21 +133,15 @@ def run_updates(system, system_update_available):

"""Users"""
for user in users:
try:
xdg_runtime_dir = get_xdg_runtime_dir(user["User"])
except KeyError as e:
log.error(f"failed to get xdg_runtime_dir for user: {user['Name']}", e)
break
log.info(f"""Running update for user: '{user['Name']}'""")

log.info(f"""Running update for user: '{user['user']}'""")
out = subprocess.run(
[
"/usr/bin/sudo",
"-u",
f"{user['Name']}",
"DISPLAY=:0",
f"XDG_RUNTIME_DIR={xdg_runtime_dir}",
f"DBUS_SESSION_BUS_ADDRESS=unix:path={xdg_runtime_dir}/bus",
"/usr/bin/systemd-run",
"--setenv=TOPGRADE_SKIP_BRKC_NOTIFY=true",
"--user",
"--machine",
f"{user['user']}@",
"--wait",
"/usr/bin/topgrade",
"--config",
"/usr/share/ublue-update/topgrade-user.toml",
Expand Down Expand Up @@ -186,7 +177,6 @@ def run_updates(system, system_update_available):


def main():

# setup argparse
parser = argparse.ArgumentParser()
parser.add_argument(
Expand Down
31 changes: 2 additions & 29 deletions src/ublue_update/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,14 @@
import json


def get_xdg_runtime_dir(uid):
out = subprocess.run(
["/usr/bin/loginctl", "show-user", f"{uid}"],
capture_output=True,
)
loginctl_output = {
line.split("=")[0]: line.split("=")[-1]
for line in out.stdout.decode("utf-8").splitlines()
}
return loginctl_output["RuntimePath"]


def get_active_sessions():
out = subprocess.run(
["/usr/bin/loginctl", "list-sessions", "--output=json"],
capture_output=True,
)
sessions = json.loads(out.stdout.decode("utf-8"))
session_properties = []
active_sessions = []
for session in sessions:
args = [
"/usr/bin/loginctl",
"show-session",
f"{session['session']}",
]
out = subprocess.run(args, capture_output=True)
if out.returncode == 0:
loginctl_output = {
line.split("=")[0]: line.split("=")[-1]
for line in out.stdout.decode("utf-8").splitlines()
}
session_properties.append(loginctl_output)
for session_info in session_properties:
graphical = session_info["Type"] == "x11" or session_info["Type"] == "wayland"
if graphical and session_info["Active"] == "yes":
active_sessions.append(session_info)
if session.get("state") == "active":
active_sessions.append(session)
return active_sessions
11 changes: 6 additions & 5 deletions tests/unit/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest
import sys
import os
from unittest.mock import patch, MagicMock, mock_open
from unittest.mock import patch, MagicMock

# Add the src directory to the sys.path
sys.path.insert(
Expand All @@ -22,7 +22,7 @@
@patch("ublue_update.cli.subprocess.run")
def test_notify_no_dbus_notify(mock_run, mock_log, mock_os, mock_cfg):
mock_cfg.dbus_notify = False
assert notify("test_title", "test_body") == None
assert notify("test_title", "test_body") is None


@patch("ublue_update.cli.cfg")
Expand All @@ -42,7 +42,7 @@ def test_notify_uid_user(mock_run, mock_log, mock_os, mock_cfg):
body,
"--app-name=Universal Blue Updater",
"--icon=software-update-available-symbolic",
f"--urgency=normal",
"--urgency=normal",
],
capture_output=True,
)
Expand All @@ -51,15 +51,15 @@ def test_notify_uid_user(mock_run, mock_log, mock_os, mock_cfg):
@patch("ublue_update.cli.cfg")
def test_ask_for_updates_no_dbus_notify(mock_cfg):
mock_cfg.dbus_notify = False
assert ask_for_updates(True) == None
assert ask_for_updates(True) is None


@patch("ublue_update.cli.cfg")
@patch("ublue_update.cli.notify")
def test_ask_for_updates_notify_none(mock_notify, mock_cfg):
mock_cfg.dbus_notify = True
mock_notify.return_value = None
assert ask_for_updates(True) == None
assert ask_for_updates(True) is None
mock_notify.assert_called_once_with(
"System Updater",
"Update available, but system checks failed. Update now?",
Expand Down Expand Up @@ -210,6 +210,7 @@ def test_run_updates_system(
["universal-blue-update-reboot=Reboot Now"],
)


@patch("ublue_update.cli.os")
@patch("ublue_update.cli.get_active_sessions")
@patch("ublue_update.cli.acquire_lock")
Expand Down
Loading

0 comments on commit e13e6ce

Please sign in to comment.