mirror of
https://github.com/freedombox/FreedomBox.git
synced 2026-11-29 08:25:10 +00:00
upgrades: Use privileged decorator for actions
Tests:
- DONE: Functional tests work
- DONE: Initial setup works
- DONE: Automatic upgrades are enable by default
- DONE: apt preferences have been updated
- DONE: Enabling backports works
- DONE: Configuration file is created
- DONE: Correct status is shown in the app page
- DONE: Enabling/disabling automatic upgrades works
- DONE: Configuration file is updated
- DONE: Correct status is shown in the app page
- DONE: Manual triggering of updates work
- DONE: Log is shown properly in the app page
- DONE: Checking for distribution upgrade works
- DONE: Distribution upgrade from stable to testing works
- DONE: When running on btrfs distribution, snapshot is created before.
- DONE: Snapshots will be disable before upgrade and re-enabled later.
- DONE: When searx is enabled before upgrade, it's uwsgi will be disabled and
re-enabled later.
- Failures due to freedombox package not being the latest version (with the
changes).
- DONE: Development Vagrant box
- DONE: Automatic updates are disabled during development setup
- DONE: Development Container
- DONE: Automatic updates are disabled during development setup
- DONE: On stable, backports are enabled when running tests
Signed-off-by: Sunil Mohan Adapa <sunil@medhas.org>
Reviewed-by: James Valleroy <jvalleroy@mailbox.org>
This commit is contained in:
1 parent
11a27d8efc
commit
66c1ddc404
5 files changed
+110
-181
No files matched your search
@@ -1,9 +1,6 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""
|
||||
FreedomBox app for upgrades.
|
||||
"""
|
||||
"""FreedomBox app for upgrades."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
@@ -13,14 +10,13 @@ from django.utils.translation import gettext_lazy as _
|
||||
from django.utils.translation import gettext_noop
|
||||
|
||||
import plinth
|
||||
from plinth import actions
|
||||
from plinth import app as app_module
|
||||
from plinth import cfg, glib, kvstore, menu
|
||||
from plinth.daemon import RelatedDaemon
|
||||
from plinth.modules.backups.components import BackupRestore
|
||||
from plinth.package import Packages
|
||||
|
||||
from . import manifest
|
||||
from . import manifest, privileged
|
||||
|
||||
first_boot_steps = [
|
||||
{
|
||||
@@ -48,10 +44,6 @@ BACKPORTS_REQUESTED_KEY = 'upgrades_backports_requested'
|
||||
|
||||
DIST_UPGRADE_ENABLED_KEY = 'upgrades_dist_upgrade_enabled'
|
||||
|
||||
SOURCES_LIST = '/etc/apt/sources.list'
|
||||
|
||||
BACKPORTS_SOURCES_LIST = '/etc/apt/sources.list.d/freedombox2.list'
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@@ -140,11 +132,11 @@ class UpgradesApp(app_module.App):
|
||||
|
||||
# Enable automatic upgrades but only on first install
|
||||
if not old_version and not cfg.develop:
|
||||
actions.superuser_run('upgrades', ['enable-auto'])
|
||||
privileged.enable_auto()
|
||||
|
||||
# Update apt preferences whenever on first install and on version
|
||||
# increment.
|
||||
actions.superuser_run('upgrades', ['setup'])
|
||||
privileged.setup()
|
||||
|
||||
# When upgrading from a version without first boot wizard for
|
||||
# backports, assume backports have been requested.
|
||||
@@ -161,30 +153,10 @@ class UpgradesApp(app_module.App):
|
||||
setup_repositories(None)
|
||||
|
||||
|
||||
def is_enabled():
|
||||
"""Return whether the module is enabled."""
|
||||
output = actions.run('upgrades', ['check-auto'])
|
||||
return 'True' in output.split()
|
||||
|
||||
|
||||
def enable():
|
||||
"""Enable the module."""
|
||||
actions.superuser_run('upgrades', ['enable-auto'])
|
||||
|
||||
|
||||
def disable():
|
||||
"""Disable the module."""
|
||||
actions.superuser_run('upgrades', ['disable-auto'])
|
||||
|
||||
|
||||
def setup_repositories(_):
|
||||
"""Setup apt repositories for backports."""
|
||||
if is_backports_requested():
|
||||
command = ['activate-backports']
|
||||
if cfg.develop:
|
||||
command.append('--develop')
|
||||
|
||||
actions.superuser_run('upgrades', command)
|
||||
privileged.activate_backports(cfg.develop)
|
||||
|
||||
|
||||
def check_dist_upgrade(_):
|
||||
@@ -196,12 +168,8 @@ def check_dist_upgrade(_):
|
||||
def try_start_dist_upgrade(test=False):
|
||||
"""Try to start dist upgrade."""
|
||||
from plinth.notification import Notification
|
||||
command = ['start-dist-upgrade']
|
||||
if test:
|
||||
command.append('--test')
|
||||
|
||||
output = actions.superuser_run('upgrades', command)
|
||||
result = json.loads(output)
|
||||
result = privileged.start_dist_upgrade(test)
|
||||
dist_upgrade_started = result['dist_upgrade_started']
|
||||
reason = result['reason']
|
||||
if 'found-previous' in reason:
|
||||
@@ -270,7 +238,7 @@ def set_dist_upgrade_enabled(enabled=True):
|
||||
|
||||
def is_backports_enabled():
|
||||
"""Return whether backports are enabled in the system configuration."""
|
||||
return os.path.exists(BACKPORTS_SOURCES_LIST)
|
||||
return os.path.exists(privileged.BACKPORTS_SOURCES_LIST)
|
||||
|
||||
|
||||
def get_current_release():
|
||||
|
||||
@@ -0,0 +1,591 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""Configure or run unattended-upgrades."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
from typing import List, Tuple, Union
|
||||
|
||||
from plinth.action_utils import (apt_hold, apt_hold_flag, apt_hold_freedombox,
|
||||
apt_unhold_freedombox, debconf_set_selections,
|
||||
is_package_manager_busy, run_apt_command,
|
||||
service_daemon_reload, service_restart)
|
||||
from plinth.actions import privileged
|
||||
from plinth.modules.apache.components import check_url
|
||||
from plinth.modules.snapshot import is_apt_snapshots_enabled
|
||||
from plinth.modules.snapshot import is_supported as snapshot_is_supported
|
||||
from plinth.modules.snapshot import load_augeas as snapshot_load_augeas
|
||||
|
||||
SOURCES_LIST = '/etc/apt/sources.list'
|
||||
BACKPORTS_SOURCES_LIST = '/etc/apt/sources.list.d/freedombox2.list'
|
||||
|
||||
AUTO_CONF_FILE = '/etc/apt/apt.conf.d/20auto-upgrades'
|
||||
LOG_FILE = '/var/log/unattended-upgrades/unattended-upgrades.log'
|
||||
DPKG_LOG_FILE = '/var/log/unattended-upgrades/unattended-upgrades-dpkg.log'
|
||||
RELEASE_FILE_URL = \
|
||||
'https://deb.debian.org/debian/dists/{}/Release'
|
||||
|
||||
APT_PREFERENCES_FREEDOMBOX = \
|
||||
'''Explanation: This file is managed by FreedomBox, do not edit.
|
||||
Explanation: Allow carefully selected updates to 'freedombox' from backports.
|
||||
Package: src:freedombox
|
||||
Pin: release a={}-backports
|
||||
Pin-Priority: 500
|
||||
'''
|
||||
|
||||
# Whenever these preferences needs to change, increment the version number
|
||||
# upgrades app. This ensures that setup is run again and the new contents are
|
||||
# overwritten on the old file.
|
||||
APT_PREFERENCES_APPS = \
|
||||
'''Explanation: This file is managed by FreedomBox, do not edit.
|
||||
Explanation: matrix-synapse shall not be available in Debian stable but
|
||||
Explanation: only in backports. Upgrade priority of packages that have needed
|
||||
Explanation: versions only in backports.
|
||||
Explanation: matrix-synapse >= 1.47.0-2 requires python3-frozendict >= 1.2-3
|
||||
Package: python3-frozendict
|
||||
Pin: release a=bullseye-backports
|
||||
Pin-Priority: 500
|
||||
|
||||
Explanation: matrix-synapse >= 1.55.0-1 requires
|
||||
Explanation: python3-typing-extensions >= 3.10
|
||||
Package: python3-typing-extensions
|
||||
Pin: release a=bullseye-backports
|
||||
Pin-Priority: 500
|
||||
|
||||
Explanation: matrix-synapse >= 1.55.0-2 requires
|
||||
Explanation: python3-jinja2 >= 3.0~
|
||||
Package: python3-jinja2
|
||||
Pin: release a=bullseye-backports
|
||||
Pin-Priority: 500
|
||||
|
||||
Explanation: python3-jinja2 >= 3.0~ requires
|
||||
Explanation: python3-markupsafe >= 2.0
|
||||
Package: python3-markupsafe
|
||||
Pin: release a=bullseye-backports
|
||||
Pin-Priority: 500
|
||||
|
||||
Explanation: matrix-synapse >= 1.59.1-1 requires
|
||||
Explanation: python3-unpaddedbase64 >= 2.1.0~
|
||||
Package: python3-unpaddedbase64
|
||||
Pin: release a=bullseye-backports
|
||||
Pin-Priority: 500
|
||||
|
||||
Explanation: matrix-synapse >= 1.65.0-1 requires
|
||||
Explanation: python3-canonicaljson >= 1.6.2~
|
||||
Package: python3-canonicaljson
|
||||
Pin: release a=bullseye-backports
|
||||
Pin-Priority: 500
|
||||
'''
|
||||
|
||||
DIST_UPGRADE_OBSOLETE_PACKAGES: List[str] = []
|
||||
|
||||
DIST_UPGRADE_PACKAGES_WITH_PROMPTS = [
|
||||
'firewalld', 'janus', 'mumble-server', 'radicale', 'roundcube-core',
|
||||
'tt-rss'
|
||||
]
|
||||
|
||||
DIST_UPGRADE_PRE_INSTALL_PACKAGES = ['base-files']
|
||||
|
||||
DIST_UPGRADE_PRE_DEBCONF_SELECTIONS: List[str] = [
|
||||
# Tell grub-pc to continue without installing grub again.
|
||||
'grub-pc grub-pc/install_devices_empty boolean true'
|
||||
]
|
||||
|
||||
DIST_UPGRADE_REQUIRED_FREE_SPACE = 5000000
|
||||
|
||||
DIST_UPGRADE_SERVICE = '''
|
||||
[Unit]
|
||||
Description=Upgrade to new stable Debian release
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/share/plinth/actions/actions upgrades dist_upgrade --no-args
|
||||
KillMode=process
|
||||
TimeoutSec=12hr
|
||||
'''
|
||||
|
||||
DIST_UPGRADE_SERVICE_PATH = \
|
||||
'/run/systemd/system/freedombox-dist-upgrade.service'
|
||||
|
||||
dist_upgrade_flag = pathlib.Path(
|
||||
'/var/lib/freedombox/dist-upgrade-in-progress')
|
||||
|
||||
|
||||
def _release_held_freedombox():
|
||||
"""If freedombox package was left in held state, release it.
|
||||
|
||||
This can happen due to an interrupted process.
|
||||
"""
|
||||
if apt_hold_flag.exists() and not is_package_manager_busy():
|
||||
apt_unhold_freedombox()
|
||||
|
||||
|
||||
@privileged
|
||||
def run():
|
||||
"""Run unattended-upgrades."""
|
||||
subprocess.run(['dpkg', '--configure', '-a'], check=False)
|
||||
run_apt_command(['--fix-broken', 'install'])
|
||||
_release_held_freedombox()
|
||||
|
||||
subprocess.Popen(['systemctl', 'start', 'freedombox-manual-upgrade'],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, close_fds=True,
|
||||
start_new_session=True)
|
||||
|
||||
|
||||
def _check_auto() -> bool:
|
||||
"""Check if automatic upgrades are enabled."""
|
||||
arguments = [
|
||||
'apt-config', 'shell', 'UpdateInterval',
|
||||
'APT::Periodic::Update-Package-Lists'
|
||||
]
|
||||
output = subprocess.check_output(arguments).decode()
|
||||
update_interval = 0
|
||||
match = re.match(r"UpdateInterval='(.*)'", output)
|
||||
if match:
|
||||
update_interval = int(match.group(1))
|
||||
|
||||
return bool(update_interval)
|
||||
|
||||
|
||||
@privileged
|
||||
def check_auto() -> bool:
|
||||
"""Check if automatic upgrades are enabled."""
|
||||
return _check_auto()
|
||||
|
||||
|
||||
@privileged
|
||||
def enable_auto():
|
||||
"""Enable automatic upgrades."""
|
||||
with open(AUTO_CONF_FILE, 'w', encoding='utf-8') as conffile:
|
||||
conffile.write('APT::Periodic::Update-Package-Lists "1";\n')
|
||||
conffile.write('APT::Periodic::Unattended-Upgrade "1";\n')
|
||||
|
||||
|
||||
@privileged
|
||||
def disable_auto():
|
||||
"""Disable automatic upgrades."""
|
||||
with open(AUTO_CONF_FILE, 'w', encoding='utf-8') as conffile:
|
||||
conffile.write('APT::Periodic::Update-Package-Lists "0";\n')
|
||||
conffile.write('APT::Periodic::Unattended-Upgrade "0";\n')
|
||||
|
||||
|
||||
@privileged
|
||||
def get_log() -> str:
|
||||
"""Return the automatic upgrades log."""
|
||||
log_lines = []
|
||||
try:
|
||||
log_lines.append('==> ' + os.path.basename(LOG_FILE))
|
||||
with open(LOG_FILE, 'r', encoding='utf-8') as file_handle:
|
||||
log_lines.append(file_handle.read())
|
||||
except IOError:
|
||||
pass
|
||||
|
||||
try:
|
||||
log_lines.append('==> ' + os.path.basename(DPKG_LOG_FILE))
|
||||
with open(DPKG_LOG_FILE, 'r', encoding='utf-8') as file_handle:
|
||||
log_lines.append(file_handle.read())
|
||||
except IOError:
|
||||
pass
|
||||
|
||||
return '\n'.join(log_lines)
|
||||
|
||||
|
||||
def _get_protocol() -> str:
|
||||
"""Return the protocol to use for newly added repository sources."""
|
||||
try:
|
||||
from plinth.modules.tor import utils
|
||||
if utils.is_apt_transport_tor_enabled():
|
||||
return 'tor+http'
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return 'http'
|
||||
|
||||
|
||||
def _is_release_file_available(protocol: str, dist: str,
|
||||
backports=False) -> bool:
|
||||
"""Return whether the release for dist[-backports] is available."""
|
||||
wrapper = None
|
||||
if protocol == 'tor+http':
|
||||
wrapper = 'torsocks'
|
||||
|
||||
if backports:
|
||||
dist += '-backports'
|
||||
|
||||
result = check_url(RELEASE_FILE_URL.format(dist), wrapper=wrapper)
|
||||
return result == 'passed'
|
||||
|
||||
|
||||
def _add_backports_sources(sources_list: str, protocol: str, dist: str):
|
||||
"""Add backports sources to freedombox repositories list."""
|
||||
sources = '''# This file is managed by FreedomBox, do not edit.
|
||||
# Allow carefully selected updates to 'freedombox' from backports.
|
||||
|
||||
deb {protocol}://deb.debian.org/debian {dist}-backports main
|
||||
deb-src {protocol}://deb.debian.org/debian {dist}-backports main
|
||||
'''
|
||||
sources = sources.format(protocol=protocol, dist=dist)
|
||||
with open(sources_list, 'w', encoding='utf-8') as file_handle:
|
||||
file_handle.write(sources)
|
||||
|
||||
|
||||
def _check_and_backports_sources(develop=False):
|
||||
"""Add backports sources after checking if it is available."""
|
||||
old_sources_list = '/etc/apt/sources.list.d/freedombox.list'
|
||||
if os.path.exists(old_sources_list):
|
||||
os.remove(old_sources_list)
|
||||
|
||||
from plinth.modules.upgrades import (get_current_release,
|
||||
is_backports_current)
|
||||
if is_backports_current():
|
||||
logging.info('Repositories list up-to-date. Skipping update.')
|
||||
return
|
||||
|
||||
try:
|
||||
with open('/etc/dpkg/origins/default', 'r',
|
||||
encoding='utf-8') as default_origin:
|
||||
matches = [
|
||||
re.match(r'Vendor:\s+Debian', line, flags=re.IGNORECASE)
|
||||
for line in default_origin.readlines()
|
||||
]
|
||||
except FileNotFoundError:
|
||||
logging.info('Could not open /etc/dpkg/origins/default')
|
||||
return
|
||||
|
||||
if not any(matches):
|
||||
logging.info('System is running a derivative of Debian. Skip enabling '
|
||||
'backports.')
|
||||
return
|
||||
|
||||
release, dist = get_current_release()
|
||||
if release == 'unstable' or (release == 'testing' and not develop):
|
||||
logging.info(f'System release is {release}. Skip enabling backports.')
|
||||
return
|
||||
|
||||
protocol = _get_protocol()
|
||||
if protocol == 'tor+http':
|
||||
logging.info('Package download over Tor is enabled.')
|
||||
|
||||
if not _is_release_file_available(protocol, dist, backports=True):
|
||||
logging.info(
|
||||
f'Release file for {dist}-backports is not available yet.')
|
||||
return
|
||||
|
||||
print(f'{dist}-backports is now available. Adding to sources.')
|
||||
_add_backports_sources(BACKPORTS_SOURCES_LIST, protocol, dist)
|
||||
# In case of dist upgrade, rewrite the preferences file.
|
||||
_add_apt_preferences()
|
||||
|
||||
|
||||
def _add_apt_preferences():
|
||||
"""Setup APT preferences to upgrade selected packages from backports."""
|
||||
base_path = pathlib.Path('/etc/apt/preferences.d')
|
||||
for file_name in ['50freedombox.pref', '50freedombox2.pref']:
|
||||
full_path = base_path / file_name
|
||||
if full_path.exists():
|
||||
full_path.unlink()
|
||||
|
||||
# Don't try to remove 50freedombox3.pref as this file is shipped with the
|
||||
# Debian package and is removed using maintainer scripts.
|
||||
|
||||
from plinth.modules.upgrades import get_current_release
|
||||
_, dist = get_current_release()
|
||||
if dist == 'sid':
|
||||
logging.info(
|
||||
f'System distribution is {dist}. Skip setting apt preferences '
|
||||
'for backports.')
|
||||
else:
|
||||
logging.info(f'Setting apt preferences for {dist}-backports.')
|
||||
with open(base_path / '50freedombox4.pref', 'w',
|
||||
encoding='utf-8') as file_handle:
|
||||
file_handle.write(APT_PREFERENCES_FREEDOMBOX.format(dist))
|
||||
with open(base_path / '51freedombox-apps.pref', 'w',
|
||||
encoding='utf-8') as file_handle:
|
||||
file_handle.write(APT_PREFERENCES_APPS)
|
||||
|
||||
|
||||
def _is_sufficient_free_space() -> bool:
|
||||
"""Return whether there is sufficient free space for dist upgrade."""
|
||||
output = subprocess.check_output(['df', '--output=avail', '/'])
|
||||
free_space = int(output.decode().split('\n')[1])
|
||||
return free_space >= DIST_UPGRADE_REQUIRED_FREE_SPACE
|
||||
|
||||
|
||||
def _check_dist_upgrade(test_upgrade=False) -> Tuple[bool, str]:
|
||||
"""Check if a distribution upgrade be performed.
|
||||
|
||||
Check for new stable release, if updates are enabled, and if there is
|
||||
enough free space for the dist upgrade.
|
||||
|
||||
If test_upgrade is True, also check for upgrade to testing.
|
||||
|
||||
Return (boolean, string) indicating if the upgrade is ready, and a reason
|
||||
if not.
|
||||
"""
|
||||
if dist_upgrade_flag.exists():
|
||||
return (True, 'found-previous')
|
||||
|
||||
from plinth.modules.upgrades import get_current_release
|
||||
release, dist = get_current_release()
|
||||
if release in ['unstable', 'testing']:
|
||||
return (False, f'already-{release}')
|
||||
|
||||
check_dists = ['stable']
|
||||
if test_upgrade:
|
||||
check_dists.append('testing')
|
||||
|
||||
codename = None
|
||||
for check_dist in check_dists:
|
||||
url = RELEASE_FILE_URL.format(check_dist)
|
||||
command = ['curl', '--silent', '--location', '--fail', url]
|
||||
protocol = _get_protocol()
|
||||
if protocol == 'tor+http':
|
||||
command.insert(0, 'torsocks')
|
||||
logging.info('Package download over Tor is enabled.')
|
||||
|
||||
try:
|
||||
output = subprocess.check_output(command).decode()
|
||||
except (subprocess.CalledProcessError, FileNotFoundError):
|
||||
logging.warning('Error while checking for new %s release',
|
||||
check_dist)
|
||||
else:
|
||||
for line in output.split('\n'):
|
||||
if line.startswith('Codename:'):
|
||||
codename = line.split()[1]
|
||||
|
||||
if not codename:
|
||||
return (False, 'codename-not-found')
|
||||
|
||||
if codename == dist:
|
||||
return (False, f'already-{dist}')
|
||||
|
||||
if not _check_auto():
|
||||
return (False, 'upgrades-not-enabled')
|
||||
|
||||
if check_dist == 'testing' and not test_upgrade:
|
||||
return (False, 'test-not-set')
|
||||
|
||||
if not _is_sufficient_free_space():
|
||||
return (False, 'not-enough-free-space')
|
||||
|
||||
logging.info('Upgrading from %s to %s...', dist, codename)
|
||||
with open(SOURCES_LIST, 'r', encoding='utf-8') as sources_list:
|
||||
lines = sources_list.readlines()
|
||||
|
||||
with open(SOURCES_LIST, 'w', encoding='utf-8') as sources_list:
|
||||
for line in lines:
|
||||
# E.g. replace 'buster' with 'bullseye'.
|
||||
new_line = line.replace(dist, codename)
|
||||
if check_dist == 'testing':
|
||||
# E.g. replace 'stable' with 'bullseye'.
|
||||
new_line = new_line.replace('stable', codename)
|
||||
|
||||
# Security suite name renamed starting with bullseye
|
||||
if 'security' in new_line:
|
||||
new_line = new_line.replace('/updates', '-security')
|
||||
|
||||
sources_list.write(new_line)
|
||||
|
||||
logging.info('Dist upgrade in progress. Setting flag.')
|
||||
dist_upgrade_flag.touch(mode=0o660)
|
||||
return (True, 'started-dist-upgrade')
|
||||
|
||||
|
||||
def _take_snapshot_and_disable() -> bool:
|
||||
"""Take a snapshot if supported and enabled, then disable snapshots.
|
||||
|
||||
Return whether snapshots shall be re-enabled at the end.
|
||||
"""
|
||||
if snapshot_is_supported():
|
||||
print('Taking a snapshot before dist upgrade...', flush=True)
|
||||
subprocess.run([
|
||||
'/usr/share/plinth/actions/actions', 'snapshot', 'create',
|
||||
'--no-args'
|
||||
], check=True)
|
||||
aug = snapshot_load_augeas()
|
||||
if is_apt_snapshots_enabled(aug):
|
||||
print('Disable apt snapshots during dist upgrade...', flush=True)
|
||||
subprocess.run([
|
||||
'/usr/share/plinth/actions/actions',
|
||||
'snapshot',
|
||||
'disable_apt_snapshot',
|
||||
], input='{"args": ["yes"], "kwargs": {}}'.encode(), check=True)
|
||||
return True
|
||||
else:
|
||||
print('Apt snapshots already disabled.', flush=True)
|
||||
else:
|
||||
print('Snapshots are not supported, skip taking a snapshot.',
|
||||
flush=True)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _restore_snapshots_config(reenable=False):
|
||||
"""Restore original snapshots configuration."""
|
||||
if reenable:
|
||||
print('Re-enable apt snapshots...', flush=True)
|
||||
subprocess.run([
|
||||
'/usr/share/plinth/actions/actions', 'snapshot',
|
||||
'disable_apt_snapshot'
|
||||
], input='{"args": ["no"], "kwargs": {}}'.encode(), check=True)
|
||||
|
||||
|
||||
def _disable_searx() -> bool:
|
||||
"""If searx is enabled, disable it until we can upgrade it properly.
|
||||
|
||||
Return whether searx was originally enabled.
|
||||
"""
|
||||
searx_is_enabled = pathlib.Path(
|
||||
'/etc/uwsgi/apps-enabled/searx.ini').exists()
|
||||
if searx_is_enabled:
|
||||
print('Disabling searx...', flush=True)
|
||||
subprocess.run(
|
||||
['/usr/share/plinth/actions/actions', 'apache', 'uwsgi_disable'],
|
||||
input='{"args": ["searx"], "kwargs": {}}'.encode(), check=True)
|
||||
|
||||
return searx_is_enabled
|
||||
|
||||
|
||||
def _update_searx(reenable=False):
|
||||
"""If searx is installed, update search engines list.
|
||||
|
||||
Re-enable if previously enabled.
|
||||
"""
|
||||
if pathlib.Path('/etc/searx/settings.yml').exists():
|
||||
print('Updating searx search engines list...', flush=True)
|
||||
subprocess.run([
|
||||
'/usr/share/plinth/actions/actions', 'searx', 'setup', '--no-args'
|
||||
], check=True)
|
||||
if reenable:
|
||||
print('Re-enabling searx after upgrade...', flush=True)
|
||||
subprocess.run([
|
||||
'/usr/share/plinth/actions/actions', 'apache', 'uwsgi_enable'
|
||||
], input='{"args": ["searx"], "kwargs": {}}'.encode(), check=True)
|
||||
|
||||
|
||||
def _perform_dist_upgrade():
|
||||
"""Perform upgrade to next release of Debian."""
|
||||
reenable_snapshots = _take_snapshot_and_disable()
|
||||
reenable_searx = _disable_searx()
|
||||
|
||||
# Hold freedombox package during entire dist upgrade.
|
||||
print('Holding freedombox package...', flush=True)
|
||||
with apt_hold_freedombox():
|
||||
print('Updating Apt cache...', flush=True)
|
||||
run_apt_command(['update'])
|
||||
|
||||
# Install packages that are necessary for unattended-upgrades
|
||||
# to start the dist upgrade.
|
||||
print(f'Upgrading packages: {DIST_UPGRADE_PRE_INSTALL_PACKAGES}...',
|
||||
flush=True)
|
||||
run_apt_command(['install'] + DIST_UPGRADE_PRE_INSTALL_PACKAGES)
|
||||
|
||||
# Pre-set debconf selections if they are required during the
|
||||
# dist upgrade.
|
||||
if DIST_UPGRADE_PRE_DEBCONF_SELECTIONS:
|
||||
print(
|
||||
f'Setting debconf selections: '
|
||||
f'{DIST_UPGRADE_PRE_DEBCONF_SELECTIONS}', flush=True)
|
||||
debconf_set_selections(DIST_UPGRADE_PRE_DEBCONF_SELECTIONS)
|
||||
|
||||
# This will upgrade most of the packages.
|
||||
print('Running unattended-upgrade...', flush=True)
|
||||
subprocess.run(['unattended-upgrade', '--verbose'], check=False)
|
||||
|
||||
# Remove obsolete packages that may prevent other packages from
|
||||
# upgrading.
|
||||
if DIST_UPGRADE_OBSOLETE_PACKAGES:
|
||||
print(f'Removing packages: {DIST_UPGRADE_OBSOLETE_PACKAGES}...',
|
||||
flush=True)
|
||||
run_apt_command(['remove'] + DIST_UPGRADE_OBSOLETE_PACKAGES)
|
||||
|
||||
# Hold packages known to have conffile prompts. FreedomBox service
|
||||
# will handle their upgrade later.
|
||||
print(
|
||||
'Holding packages with conffile prompts: ' +
|
||||
', '.join(DIST_UPGRADE_PACKAGES_WITH_PROMPTS) + '...', flush=True)
|
||||
with apt_hold(DIST_UPGRADE_PACKAGES_WITH_PROMPTS):
|
||||
print('Running apt full-upgrade...', flush=True)
|
||||
run_apt_command(['full-upgrade'])
|
||||
|
||||
_update_searx(reenable_searx)
|
||||
|
||||
print('Running apt autoremove...', flush=True)
|
||||
run_apt_command(['autoremove'])
|
||||
|
||||
# Run unattended-upgrade once more to handle upgrading the
|
||||
# freedombox package.
|
||||
print('Running unattended-upgrade...', flush=True)
|
||||
subprocess.run(['unattended-upgrade', '--verbose'], check=False)
|
||||
|
||||
_restore_snapshots_config(reenable_snapshots)
|
||||
|
||||
# Restart FreedomBox service to ensure it is using the latest
|
||||
# dependencies.
|
||||
print('Restarting FreedomBox service...', flush=True)
|
||||
service_restart('plinth')
|
||||
|
||||
# After 10 minutes, update apt cache again to trigger force_upgrades.
|
||||
print('Waiting for 10 minutes...', flush=True)
|
||||
time.sleep(10 * 60)
|
||||
print('Updating Apt cache...', flush=True)
|
||||
run_apt_command(['update'])
|
||||
|
||||
print('Dist upgrade complete. Removing flag.', flush=True)
|
||||
if dist_upgrade_flag.exists():
|
||||
dist_upgrade_flag.unlink()
|
||||
|
||||
|
||||
@privileged
|
||||
def setup():
|
||||
"""Setup apt preferences."""
|
||||
_add_apt_preferences()
|
||||
|
||||
|
||||
@privileged
|
||||
def activate_backports(develop: bool = False):
|
||||
"""Setup software repositories needed for FreedomBox.
|
||||
|
||||
Repositories list for now only contains the backports. If the file exists,
|
||||
assume that it contains backports.
|
||||
"""
|
||||
_check_and_backports_sources(develop)
|
||||
|
||||
|
||||
def _start_dist_upgrade_service():
|
||||
"""Create dist upgrade service and start it."""
|
||||
with open(DIST_UPGRADE_SERVICE_PATH, 'w',
|
||||
encoding='utf-8') as service_file:
|
||||
service_file.write(DIST_UPGRADE_SERVICE)
|
||||
|
||||
service_daemon_reload()
|
||||
subprocess.Popen(['systemctl', 'start', 'freedombox-dist-upgrade'],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, close_fds=True,
|
||||
start_new_session=True)
|
||||
|
||||
|
||||
@privileged
|
||||
def start_dist_upgrade(test: bool = False) -> dict[str, Union[str, bool]]:
|
||||
"""Start dist upgrade process.
|
||||
|
||||
Check if a new stable release is available, and start dist-upgrade process
|
||||
if updates are enabled.
|
||||
"""
|
||||
_release_held_freedombox()
|
||||
|
||||
upgrade_ready, reason = _check_dist_upgrade(test)
|
||||
if upgrade_ready:
|
||||
_start_dist_upgrade_service()
|
||||
|
||||
return {'dist_upgrade_started': upgrade_ready, 'reason': reason}
|
||||
|
||||
|
||||
@privileged
|
||||
def dist_upgrade():
|
||||
"""Perform major distribution upgrade."""
|
||||
_perform_dist_upgrade()
|
||||
@@ -1,7 +1,6 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
"""
|
||||
FreedomBox app for upgrades.
|
||||
"""
|
||||
"""FreedomBox app for upgrades."""
|
||||
|
||||
import subprocess
|
||||
|
||||
from apt.cache import Cache
|
||||
@@ -13,34 +12,37 @@ from django.utils.translation import gettext as _
|
||||
from django.views.generic import TemplateView
|
||||
from django.views.generic.edit import FormView
|
||||
|
||||
from plinth import __version__, actions, package
|
||||
from plinth.errors import ActionError
|
||||
from plinth import __version__, package
|
||||
from plinth.modules import first_boot, upgrades
|
||||
from plinth.views import AppView
|
||||
|
||||
from . import privileged
|
||||
from .forms import BackportsFirstbootForm, ConfigureForm, UpdateFirstbootForm
|
||||
|
||||
|
||||
class UpgradesConfigurationView(AppView):
|
||||
"""Serve configuration page."""
|
||||
|
||||
form_class = ConfigureForm
|
||||
success_url = reverse_lazy('upgrades:index')
|
||||
template_name = "upgrades_configure.html"
|
||||
app_id = 'upgrades'
|
||||
|
||||
def get_initial(self):
|
||||
"""Return the initial values for the form."""
|
||||
return {
|
||||
'auto_upgrades_enabled': upgrades.is_enabled(),
|
||||
'auto_upgrades_enabled': privileged.check_auto(),
|
||||
'dist_upgrade_enabled': upgrades.is_dist_upgrade_enabled()
|
||||
}
|
||||
|
||||
def get_context_data(self, *args, **kwargs):
|
||||
"""Add additional context data for template."""
|
||||
context = super().get_context_data(*args, **kwargs)
|
||||
context['can_activate_backports'] = upgrades.can_activate_backports()
|
||||
context['is_backports_requested'] = upgrades.is_backports_requested()
|
||||
context['is_busy'] = (_is_updating()
|
||||
or package.is_package_manager_busy())
|
||||
context['log'] = get_log()
|
||||
context['log'] = privileged.get_log()
|
||||
context['refresh_page_sec'] = 3 if context['is_busy'] else None
|
||||
context['version'] = __version__
|
||||
context['new_version'] = is_newer_version_available()
|
||||
@@ -58,10 +60,10 @@ class UpgradesConfigurationView(AppView):
|
||||
|
||||
try:
|
||||
if new_status['auto_upgrades_enabled']:
|
||||
upgrades.enable()
|
||||
privileged.enable_auto()
|
||||
else:
|
||||
upgrades.disable()
|
||||
except ActionError as exception:
|
||||
privileged.disable_auto()
|
||||
except Exception as exception:
|
||||
error = exception.args[2]
|
||||
messages.error(
|
||||
self.request,
|
||||
@@ -89,14 +91,14 @@ class UpgradesConfigurationView(AppView):
|
||||
|
||||
|
||||
def is_newer_version_available():
|
||||
"""Returns whether a newer Freedombox version is available."""
|
||||
"""Return whether a newer Freedombox version is available."""
|
||||
cache = Cache()
|
||||
freedombox = cache['freedombox']
|
||||
return not freedombox.candidate.is_installed
|
||||
|
||||
|
||||
def get_os_release():
|
||||
"""Returns the Debian release number and name."""
|
||||
"""Return the Debian release number and name."""
|
||||
output = 'Error: Cannot read PRETTY_NAME in /etc/os-release.'
|
||||
with open('/etc/os-release', 'r', encoding='utf-8') as release_file:
|
||||
for line in release_file:
|
||||
@@ -107,11 +109,6 @@ def get_os_release():
|
||||
return output
|
||||
|
||||
|
||||
def get_log():
|
||||
"""Return the current log for unattended upgrades."""
|
||||
return actions.superuser_run('upgrades', ['get-log'])
|
||||
|
||||
|
||||
def _is_updating():
|
||||
"""Check if manually triggered update is running."""
|
||||
command = ['systemctl', 'is-active', 'freedombox-manual-upgrade']
|
||||
@@ -124,9 +121,9 @@ def upgrade(request):
|
||||
"""Serve the upgrade page."""
|
||||
if request.method == 'POST':
|
||||
try:
|
||||
actions.superuser_run('upgrades', ['run'])
|
||||
privileged.run()
|
||||
messages.success(request, _('Upgrade process started.'))
|
||||
except ActionError:
|
||||
except Exception:
|
||||
messages.error(request, _('Starting upgrade failed.'))
|
||||
|
||||
return redirect(reverse_lazy('upgrades:index'))
|
||||
@@ -144,6 +141,7 @@ def activate_backports(request):
|
||||
|
||||
class BackportsFirstbootView(FormView):
|
||||
"""View to configure backports during first boot wizard."""
|
||||
|
||||
template_name = 'backports-firstboot.html'
|
||||
form_class = BackportsFirstbootForm
|
||||
|
||||
@@ -179,6 +177,7 @@ class BackportsFirstbootView(FormView):
|
||||
|
||||
class UpdateFirstbootView(FormView):
|
||||
"""View to run initial update during first boot wizard."""
|
||||
|
||||
template_name = 'update-firstboot.html'
|
||||
form_class = UpdateFirstbootForm
|
||||
|
||||
@@ -197,7 +196,7 @@ class UpdateFirstbootView(FormView):
|
||||
"""Run update if selected, and mark step as done."""
|
||||
self.update = form.cleaned_data['update_now']
|
||||
if self.update:
|
||||
actions.superuser_run('upgrades', ['run'])
|
||||
privileged.run()
|
||||
|
||||
first_boot.mark_step_done('initial_update')
|
||||
return super().form_valid(form)
|
||||
@@ -205,6 +204,7 @@ class UpdateFirstbootView(FormView):
|
||||
|
||||
class UpdateFirstbootProgressView(TemplateView):
|
||||
"""View to show initial update progress."""
|
||||
|
||||
template_name = 'update-firstboot-progress.html'
|
||||
|
||||
def get_context_data(self, *args, **kwargs):
|
||||
|
||||
Reference in new issue
Block a user