Blame SOURCES/0025-Move-system-upgrade-plugin-to-core-RhBug-2054235.patch

888f85
From 54eba8059b07b31b2caa27b48269e74da959eaa6 Mon Sep 17 00:00:00 2001
888f85
From: Jan Kolarik <jkolarik@redhat.com>
888f85
Date: Thu, 22 Sep 2022 16:02:55 +0000
888f85
Subject: [PATCH] Move system-upgrade plugin to core (RhBug:2054235)
888f85
888f85
= changelog =
888f85
type: bugfix
888f85
resolves: https://bugzilla.redhat.com/show_bug.cgi?id=2054235
888f85
---
888f85
 CMakeLists.txt                                |  15 +
888f85
 dnf-plugins-core.spec                         |  38 +-
888f85
 doc/CMakeLists.txt                            |   1 +
888f85
 doc/conf.py                                   |   1 +
888f85
 doc/index.rst                                 |   1 +
888f85
 doc/system-upgrade.rst                        | 207 ++++++
888f85
 etc/CMakeLists.txt                            |   1 +
888f85
 etc/systemd/CMakeLists.txt                    |   1 +
888f85
 .../dnf-system-upgrade-cleanup.service        |  11 +
888f85
 etc/systemd/dnf-system-upgrade.service        |  20 +
888f85
 plugins/CMakeLists.txt                        |   1 +
888f85
 plugins/system_upgrade.py                     | 699 ++++++++++++++++++
888f85
 tests/test_system_upgrade.py                  | 502 +++++++++++++
888f85
 13 files changed, 1494 insertions(+), 4 deletions(-)
888f85
 create mode 100644 doc/system-upgrade.rst
888f85
 create mode 100644 etc/systemd/CMakeLists.txt
888f85
 create mode 100644 etc/systemd/dnf-system-upgrade-cleanup.service
888f85
 create mode 100644 etc/systemd/dnf-system-upgrade.service
888f85
 create mode 100644 plugins/system_upgrade.py
888f85
 create mode 100644 tests/test_system_upgrade.py
888f85
888f85
diff --git a/CMakeLists.txt b/CMakeLists.txt
888f85
index f143905..bd5f35b 100644
888f85
--- a/CMakeLists.txt
888f85
+++ b/CMakeLists.txt
888f85
@@ -23,6 +23,21 @@ MESSAGE(STATUS "Python install dir is ${PYTHON_INSTALL_DIR}")
888f85
 
888f85
 SET (SYSCONFDIR /etc)
888f85
 
888f85
+find_package (PkgConfig)
888f85
+
888f85
+if (PKG_CONFIG_FOUND)
888f85
+  pkg_search_module (SYSTEMD systemd)
888f85
+  if (SYSTEMD_FOUND)
888f85
+    execute_process (COMMAND ${PKG_CONFIG_EXECUTABLE} --variable=systemdsystemunitdir systemd
888f85
+                     OUTPUT_VARIABLE SYSTEMD_DIR
888f85
+                     OUTPUT_STRIP_TRAILING_WHITESPACE)
888f85
+  endif ()
888f85
+endif()
888f85
+
888f85
+if (NOT SYSTEMD_DIR)
888f85
+  set (SYSTEMD_DIR /usr/lib/systemd/system)
888f85
+endif ()
888f85
+
888f85
 ADD_SUBDIRECTORY (libexec)
888f85
 ADD_SUBDIRECTORY (doc)
888f85
 ADD_SUBDIRECTORY (etc)
888f85
diff --git a/dnf-plugins-core.spec b/dnf-plugins-core.spec
888f85
index afdbcbb..0e1c9e3 100644
888f85
--- a/dnf-plugins-core.spec
888f85
+++ b/dnf-plugins-core.spec
888f85
@@ -64,6 +64,9 @@ Provides:       dnf-command(repograph)
888f85
 Provides:       dnf-command(repomanage)
888f85
 Provides:       dnf-command(reposync)
888f85
 Provides:       dnf-command(repodiff)
888f85
+Provides:       dnf-command(system-upgrade)
888f85
+Provides:       dnf-command(offline-upgrade)
888f85
+Provides:       dnf-command(offline-distrosync)
888f85
 Provides:       dnf-plugins-extras-debug = %{version}-%{release}
888f85
 Provides:       dnf-plugins-extras-repoclosure = %{version}-%{release}
888f85
 Provides:       dnf-plugins-extras-repograph = %{version}-%{release}
888f85
@@ -80,6 +83,7 @@ Provides:       dnf-plugin-repodiff = %{version}-%{release}
888f85
 Provides:       dnf-plugin-repograph = %{version}-%{release}
888f85
 Provides:       dnf-plugin-repomanage = %{version}-%{release}
888f85
 Provides:       dnf-plugin-reposync = %{version}-%{release}
888f85
+Provides:       dnf-plugin-system-upgrade = %{version}-%{release}
888f85
 %if %{with yumcompatibility}
888f85
 Provides:       yum-plugin-copr = %{version}-%{release}
888f85
 Provides:       yum-plugin-changelog = %{version}-%{release}
888f85
@@ -133,8 +137,8 @@ Conflicts:      python-%{name} < %{version}-%{release}
888f85
 %description -n python2-%{name}
888f85
 Core Plugins for DNF, Python 2 interface. This package enhances DNF with builddep,
888f85
 config-manager, copr, degug, debuginfo-install, download, needs-restarting,
888f85
-groups-manager, repoclosure, repograph, repomanage, reposync, changelog
888f85
-and repodiff commands.
888f85
+groups-manager, repoclosure, repograph, repomanage, reposync, changelog,
888f85
+repodiff, system-upgrade, offline-upgrade and offline-distrosync commands.
888f85
 Additionally provides generate_completion_cache passive plugin.
888f85
 %endif
888f85
 
888f85
@@ -145,6 +149,10 @@ Summary:    Core Plugins for DNF
888f85
 BuildRequires:  python3-dbus
888f85
 BuildRequires:  python3-devel
888f85
 BuildRequires:  python3-dnf >= %{dnf_lowest_compatible}
888f85
+BuildRequires:  python3-systemd
888f85
+BuildRequires:  pkgconfig(systemd)
888f85
+BuildRequires:  systemd
888f85
+%{?systemd_ordering}
888f85
 %if 0%{?fedora}
888f85
 Requires:       python3-distro
888f85
 %endif
888f85
@@ -152,14 +160,17 @@ Requires:       python3-dbus
888f85
 Requires:       python3-dnf >= %{dnf_lowest_compatible}
888f85
 Requires:       python3-hawkey >= %{hawkey_version}
888f85
 Requires:       python3-dateutil
888f85
+Requires:       python3-systemd
888f85
 Provides:       python3-dnf-plugins-extras-debug = %{version}-%{release}
888f85
 Provides:       python3-dnf-plugins-extras-repoclosure = %{version}-%{release}
888f85
 Provides:       python3-dnf-plugins-extras-repograph = %{version}-%{release}
888f85
 Provides:       python3-dnf-plugins-extras-repomanage = %{version}-%{release}
888f85
+Provides:       python3-dnf-plugin-system-upgrade = %{version}-%{release}
888f85
 Obsoletes:      python3-dnf-plugins-extras-debug < %{dnf_plugins_extra}
888f85
 Obsoletes:      python3-dnf-plugins-extras-repoclosure < %{dnf_plugins_extra}
888f85
 Obsoletes:      python3-dnf-plugins-extras-repograph < %{dnf_plugins_extra}
888f85
 Obsoletes:      python3-dnf-plugins-extras-repomanage < %{dnf_plugins_extra}
888f85
+Obsoletes:      python3-dnf-plugin-system-upgrade < %{version}-%{release}
888f85
 
888f85
 Conflicts:      %{name} <= 0.1.5
888f85
 # let the both python plugin versions be updated simultaneously
888f85
@@ -169,8 +180,8 @@ Conflicts:      python-%{name} < %{version}-%{release}
888f85
 %description -n python3-%{name}
888f85
 Core Plugins for DNF, Python 3 interface. This package enhances DNF with builddep,
888f85
 config-manager, copr, debug, debuginfo-install, download, needs-restarting,
888f85
-groups-manager, repoclosure, repograph, repomanage, reposync, changelog
888f85
-and repodiff commands.
888f85
+groups-manager, repoclosure, repograph, repomanage, reposync, changelog,
888f85
+repodiff, system-upgrade, offline-upgrade and offline-distrosync commands.
888f85
 Additionally provides generate_completion_cache passive plugin.
888f85
 %endif
888f85
 
888f85
@@ -451,6 +462,17 @@ pushd build-py3
888f85
   %make_install
888f85
 popd
888f85
 %endif
888f85
+
888f85
+%if %{with python3}
888f85
+mkdir -p %{buildroot}%{_unitdir}/system-update.target.wants/
888f85
+pushd %{buildroot}%{_unitdir}/system-update.target.wants/
888f85
+  ln -sr ../dnf-system-upgrade.service
888f85
+popd
888f85
+
888f85
+ln -sf %{_mandir}/man8/dnf-system-upgrade.8.gz %{buildroot}%{_mandir}/man8/dnf-offline-upgrade.8.gz
888f85
+ln -sf %{_mandir}/man8/dnf-system-upgrade.8.gz %{buildroot}%{_mandir}/man8/dnf-offline-distrosync.8.gz
888f85
+%endif
888f85
+
888f85
 %find_lang %{name}
888f85
 %if %{with yumutils}
888f85
   %if %{with python3}
888f85
@@ -515,6 +537,9 @@ ln -sf %{_mandir}/man1/%{yum_utils_subpackage_name}.1.gz %{buildroot}%{_mandir}/
888f85
 %{_mandir}/man8/dnf-repograph.*
888f85
 %{_mandir}/man8/dnf-repomanage.*
888f85
 %{_mandir}/man8/dnf-reposync.*
888f85
+%{_mandir}/man8/dnf-system-upgrade.*
888f85
+%{_mandir}/man8/dnf-offline-upgrade.*
888f85
+%{_mandir}/man8/dnf-offline-distrosync.*
888f85
 %if %{with yumcompatibility}
888f85
 %{_mandir}/man1/yum-changelog.*
888f85
 %{_mandir}/man8/yum-copr.*
888f85
@@ -572,6 +597,7 @@ ln -sf %{_mandir}/man1/%{yum_utils_subpackage_name}.1.gz %{buildroot}%{_mandir}/
888f85
 %{python3_sitelib}/dnf-plugins/repograph.py
888f85
 %{python3_sitelib}/dnf-plugins/repomanage.py
888f85
 %{python3_sitelib}/dnf-plugins/reposync.py
888f85
+%{python3_sitelib}/dnf-plugins/system_upgrade.py
888f85
 %{python3_sitelib}/dnf-plugins/__pycache__/builddep.*
888f85
 %{python3_sitelib}/dnf-plugins/__pycache__/changelog.*
888f85
 %{python3_sitelib}/dnf-plugins/__pycache__/config_manager.*
888f85
@@ -587,7 +613,11 @@ ln -sf %{_mandir}/man1/%{yum_utils_subpackage_name}.1.gz %{buildroot}%{_mandir}/
888f85
 %{python3_sitelib}/dnf-plugins/__pycache__/repograph.*
888f85
 %{python3_sitelib}/dnf-plugins/__pycache__/repomanage.*
888f85
 %{python3_sitelib}/dnf-plugins/__pycache__/reposync.*
888f85
+%{python3_sitelib}/dnf-plugins/__pycache__/system_upgrade.*
888f85
 %{python3_sitelib}/dnfpluginscore/
888f85
+%{_unitdir}/dnf-system-upgrade.service
888f85
+%{_unitdir}/dnf-system-upgrade-cleanup.service
888f85
+%{_unitdir}/system-update.target.wants/dnf-system-upgrade.service
888f85
 %endif
888f85
 
888f85
 %if %{with yumutils}
888f85
diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt
888f85
index ff84cf8..79472a5 100644
888f85
--- a/doc/CMakeLists.txt
888f85
+++ b/doc/CMakeLists.txt
888f85
@@ -37,6 +37,7 @@ INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/dnf-builddep.8
888f85
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-reposync.8
888f85
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-post-transaction-actions.8
888f85
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-show-leaves.8
888f85
+    ${CMAKE_CURRENT_BINARY_DIR}/dnf-system-upgrade.8
888f85
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-versionlock.8
888f85
     ${CMAKE_CURRENT_BINARY_DIR}/yum-copr.8
888f85
     ${CMAKE_CURRENT_BINARY_DIR}/yum-versionlock.8
888f85
diff --git a/doc/conf.py b/doc/conf.py
888f85
index 41d6936..327ac07 100644
888f85
--- a/doc/conf.py
888f85
+++ b/doc/conf.py
888f85
@@ -264,6 +264,7 @@ man_pages = [
888f85
     ('post-transaction-actions', 'dnf-post-transaction-actions',
888f85
      u'DNF post transaction actions Plugin', AUTHORS, 8),
888f85
     ('show-leaves', 'dnf-show-leaves', u'DNF show-leaves Plugin', AUTHORS, 8),
888f85
+    ('system-upgrade', 'dnf-system-upgrade', u'DNF system-upgrade Plugin', AUTHORS, 8),
888f85
     ('versionlock', 'dnf-versionlock', u'DNF versionlock Plugin', AUTHORS, 8),
888f85
 
888f85
     # yum3 compatible layer for manpages
888f85
diff --git a/doc/index.rst b/doc/index.rst
888f85
index 07f6052..251a24e 100644
888f85
--- a/doc/index.rst
888f85
+++ b/doc/index.rst
888f85
@@ -46,6 +46,7 @@ This documents core plugins of DNF:
888f85
    repomanage
888f85
    reposync
888f85
    show-leaves
888f85
+   system-upgrade
888f85
    versionlock
888f85
 
888f85
 
888f85
diff --git a/doc/system-upgrade.rst b/doc/system-upgrade.rst
888f85
new file mode 100644
888f85
index 0000000..3110460
888f85
--- /dev/null
888f85
+++ b/doc/system-upgrade.rst
888f85
@@ -0,0 +1,207 @@
888f85
+..
888f85
+  Copyright (C) 2014-2016 Red Hat, Inc.
888f85
+
888f85
+  This copyrighted material is made available to anyone wishing to use,
888f85
+  modify, copy, or redistribute it subject to the terms and conditions of
888f85
+  the GNU General Public License v.2, or (at your option) any later version.
888f85
+  This program is distributed in the hope that it will be useful, but WITHOUT
888f85
+  ANY WARRANTY expressed or implied, including the implied warranties of
888f85
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
888f85
+  Public License for more details.  You should have received a copy of the
888f85
+  GNU General Public License along with this program; if not, write to the
888f85
+  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
888f85
+  02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
888f85
+  source code or documentation are not subject to the GNU General Public
888f85
+  License and may only be used or replicated with the express permission of
888f85
+  Red Hat, Inc.
888f85
+
888f85
+=========================
888f85
+DNF system-upgrade Plugin
888f85
+=========================
888f85
+
888f85
+-----------
888f85
+Description
888f85
+-----------
888f85
+
888f85
+DNF system-upgrades plugin provides three commands: ``system-upgrade``, ``offline-upgrade``, and
888f85
+``offline-distrosync``. Only ``system-upgrade`` command requires increase of distribution major
888f85
+version (``--releasever``) compared to installed version.
888f85
+
888f85
+``dnf system-upgrade`` can be used to upgrade a Fedora system to a new major
888f85
+release. It replaces fedup (the old Fedora Upgrade tool). Before you proceed ensure that your system
888f85
+is fully upgraded (``dnf --refresh upgrade``).
888f85
+
888f85
+The ``system-upgrade`` command also performes additional actions necessary for the upgrade of the
888f85
+system, for example an upgrade of groups and environments.
888f85
+
888f85
+--------
888f85
+Synopsis
888f85
+--------
888f85
+
888f85
+``dnf system-upgrade download --releasever VERSION [OPTIONS]``
888f85
+
888f85
+``dnf system-upgrade reboot``
888f85
+
888f85
+``dnf system-upgrade clean``
888f85
+
888f85
+``dnf system-upgrade log``
888f85
+
888f85
+``dnf system-upgrade log --number=<number>``
888f85
+
888f85
+``dnf offline-upgrade download [OPTIONS]``
888f85
+
888f85
+``dnf offline-upgrade reboot``
888f85
+
888f85
+``dnf offline-upgrade clean``
888f85
+
888f85
+``dnf offline-upgrade log``
888f85
+
888f85
+``dnf offline-upgrade log --number=<number>``
888f85
+
888f85
+``dnf offline-distrosync download [OPTIONS]``
888f85
+
888f85
+``dnf offline-distrosync reboot``
888f85
+
888f85
+``dnf offline-distrosync clean``
888f85
+
888f85
+``dnf offline-distrosync log``
888f85
+
888f85
+``dnf offline-distrosync log --number=<number>``
888f85
+
888f85
+-----------
888f85
+Subcommands
888f85
+-----------
888f85
+
888f85
+``download``
888f85
+    Downloads everything needed to upgrade to a new major release.
888f85
+
888f85
+``reboot``
888f85
+    Prepares the system to perform the upgrade, and reboots to start the upgrade.
888f85
+    This can only be used after the ``download`` command completes successfully.
888f85
+
888f85
+``clean``
888f85
+    Remove previously-downloaded data. This happens automatically at the end of
888f85
+    a successful upgrade.
888f85
+
888f85
+``log``
888f85
+    Used to see a list of boots during which an upgrade was attempted, or show
888f85
+    the logs from an upgrade attempt. The logs for one of the boots can be shown
888f85
+    by specifying one of the numbers in the first column. Negative numbers can
888f85
+    be used to number the boots from last to first. For example, ``log --number=-1`` can
888f85
+    be used to see the logs for the last upgrade attempt.
888f85
+
888f85
+-------
888f85
+Options
888f85
+-------
888f85
+
888f85
+``--releasever=VERSION``
888f85
+    REQUIRED. The version to upgrade to. Sets ``$releasever`` in all enabled
888f85
+    repos. Usually a number, or ``rawhide``.
888f85
+
888f85
+``--downloaddir=<path>``
888f85
+    Redirect download of packages to provided ``<path>``. By default, packages
888f85
+    are downloaded into (per repository created) subdirectories of
888f85
+    /var/lib/dnf/system-upgrade.
888f85
+
888f85
+``--distro-sync``
888f85
+    Behave like ``dnf distro-sync``: always install packages from the new
888f85
+    release, even if they are older than the currently-installed version. This
888f85
+    is the default behavior.
888f85
+
888f85
+``--no-downgrade``
888f85
+    Behave like ``dnf update``: do not install packages from the new release
888f85
+    if they are older than what is currently installed. This is the opposite of
888f85
+    ``--distro-sync``. If both are specified, the last option will be used. The option cannot be
888f85
+    used with the ``offline-distrosync`` command.
888f85
+
888f85
+``--number``
888f85
+    Applied with ``log`` subcommand will show the log specified by the number.
888f85
+
888f85
+-----
888f85
+Notes
888f85
+-----
888f85
+
888f85
+``dnf system-upgrade reboot`` does not create a "System Upgrade" boot item. The
888f85
+upgrade will start regardless of which boot item is chosen.
888f85
+
888f85
+The ``DNF_SYSTEM_UPGRADE_NO_REBOOT`` environment variable can be set to a
888f85
+non-empty value to disable the actual reboot performed by ``system-upgrade``
888f85
+(e.g. for testing purposes).
888f85
+
888f85
+Since this is a DNF plugin, options accepted by ``dnf`` are also valid here,
888f85
+such as ``--allowerasing``.
888f85
+See :manpage:`dnf(8)` for more information.
888f85
+
888f85
+The ``fedup`` command is not provided, not even as an alias for
888f85
+``dnf system-upgrade``.
888f85
+
888f85
+----
888f85
+Bugs
888f85
+----
888f85
+
888f85
+Upgrading from install media (e.g. a DVD or .iso file) currently requires the
888f85
+user to manually set up a DNF repo and fstab entry for the media.
888f85
+
888f85
+--------
888f85
+Examples
888f85
+--------
888f85
+
888f85
+Typical upgrade usage
888f85
+---------------------
888f85
+
888f85
+``dnf --refresh upgrade``
888f85
+
888f85
+``dnf system-upgrade download --releasever 26``
888f85
+
888f85
+``dnf system-upgrade reboot``
888f85
+
888f85
+Show logs from last upgrade attempt
888f85
+-----------------------------------
888f85
+
888f85
+``dnf system-upgrade log --number=-1``
888f85
+
888f85
+--------------
888f85
+Reporting Bugs
888f85
+--------------
888f85
+
888f85
+Bugs should be filed here:
888f85
+
888f85
+  https://bugzilla.redhat.com/
888f85
+
888f85
+For more info on filing bugs, see the Fedora Project wiki:
888f85
+
888f85
+  https://fedoraproject.org/wiki/How_to_file_a_bug_report
888f85
+
888f85
+  https://fedoraproject.org/wiki/Bugs_and_feature_requests
888f85
+
888f85
+Please include ``/var/log/dnf.log`` and the output of
888f85
+``dnf system-upgrade log --number=-1`` (if applicable) in your bug reports.
888f85
+
888f85
+Problems with dependency solving during download are best reported to the
888f85
+maintainers of the package(s) with the dependency problems.
888f85
+
888f85
+Similarly, problems encountered on your system after the upgrade completes
888f85
+should be reported to the maintainers of the affected components. In other
888f85
+words: if (for example) KDE stops working, it's best if you report that to
888f85
+the KDE maintainers.
888f85
+
888f85
+--------
888f85
+See Also
888f85
+--------
888f85
+
888f85
+:manpage:`dnf(8)`,
888f85
+:manpage:`dnf.conf(5)`,
888f85
+:manpage:`journalctl(1)`.
888f85
+
888f85
+Project homepage
888f85
+----------------
888f85
+
888f85
+https://github.com/rpm-software-management/dnf-plugins-core
888f85
+
888f85
+-------
888f85
+Authors
888f85
+-------
888f85
+
888f85
+Will Woods <wwoods@redhat.com>
888f85
+
888f85
+Štěpán Smetana <ssmetana@redhat.com>
888f85
diff --git a/etc/CMakeLists.txt b/etc/CMakeLists.txt
888f85
index 2e9cccd..a892f8a 100644
888f85
--- a/etc/CMakeLists.txt
888f85
+++ b/etc/CMakeLists.txt
888f85
@@ -1 +1,2 @@
888f85
 ADD_SUBDIRECTORY (dnf)
888f85
+ADD_SUBDIRECTORY (systemd)
888f85
diff --git a/etc/systemd/CMakeLists.txt b/etc/systemd/CMakeLists.txt
888f85
new file mode 100644
888f85
index 0000000..8a29403
888f85
--- /dev/null
888f85
+++ b/etc/systemd/CMakeLists.txt
888f85
@@ -0,0 +1 @@
888f85
+INSTALL (FILES "dnf-system-upgrade.service" "dnf-system-upgrade-cleanup.service" DESTINATION ${SYSTEMD_DIR})
888f85
diff --git a/etc/systemd/dnf-system-upgrade-cleanup.service b/etc/systemd/dnf-system-upgrade-cleanup.service
888f85
new file mode 100644
888f85
index 0000000..49f771c
888f85
--- /dev/null
888f85
+++ b/etc/systemd/dnf-system-upgrade-cleanup.service
888f85
@@ -0,0 +1,11 @@
888f85
+[Unit]
888f85
+Description=System Upgrade using DNF failed
888f85
+DefaultDependencies=no
888f85
+
888f85
+[Service]
888f85
+Type=oneshot
888f85
+# Remove the symlink if it's still there, to protect against reboot loops.
888f85
+ExecStart=/usr/bin/rm -fv /system-update
888f85
+# If anything goes wrong, reboot back to the normal system.
888f85
+ExecStart=/usr/bin/systemctl --no-block reboot
888f85
+
888f85
diff --git a/etc/systemd/dnf-system-upgrade.service b/etc/systemd/dnf-system-upgrade.service
888f85
new file mode 100644
888f85
index 0000000..2d23cfe
888f85
--- /dev/null
888f85
+++ b/etc/systemd/dnf-system-upgrade.service
888f85
@@ -0,0 +1,20 @@
888f85
+[Unit]
888f85
+Description=System Upgrade using DNF
888f85
+ConditionPathExists=/system-update
888f85
+Documentation=http://www.freedesktop.org/wiki/Software/systemd/SystemUpdates
888f85
+
888f85
+DefaultDependencies=no
888f85
+Requires=sysinit.target
888f85
+After=sysinit.target systemd-journald.socket system-update-pre.target
888f85
+Before=shutdown.target system-update.target
888f85
+OnFailure=dnf-system-upgrade-cleanup.service
888f85
+
888f85
+[Service]
888f85
+# We are done when the script exits, not before
888f85
+Type=oneshot
888f85
+# Upgrade output goes to journal and on-screen.
888f85
+StandardOutput=journal+console
888f85
+ExecStart=/usr/bin/dnf system-upgrade upgrade
888f85
+
888f85
+[Install]
888f85
+WantedBy=system-update.target
888f85
diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt
888f85
index 59f148f..d004e5e 100644
888f85
--- a/plugins/CMakeLists.txt
888f85
+++ b/plugins/CMakeLists.txt
888f85
@@ -22,6 +22,7 @@ INSTALL (FILES repograph.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
888f85
 INSTALL (FILES repomanage.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
888f85
 INSTALL (FILES reposync.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
888f85
 INSTALL (FILES show_leaves.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
888f85
+INSTALL (FILES system_upgrade.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
888f85
 INSTALL (FILES modulesync.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
888f85
 INSTALL (FILES versionlock.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
888f85
 
888f85
diff --git a/plugins/system_upgrade.py b/plugins/system_upgrade.py
888f85
new file mode 100644
888f85
index 0000000..fee6762
888f85
--- /dev/null
888f85
+++ b/plugins/system_upgrade.py
888f85
@@ -0,0 +1,699 @@
888f85
+# -*- coding: utf-8 -*-
888f85
+#
888f85
+# Copyright (c) 2015-2020 Red Hat, Inc.
888f85
+#
888f85
+# This program is free software; you can redistribute it and/or modify
888f85
+# it under the terms of the GNU General Public License as published by
888f85
+# the Free Software Foundation; either version 2 of the License, or
888f85
+# (at your option) any later version.
888f85
+#
888f85
+# This program is distributed in the hope that it will be useful,
888f85
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
888f85
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
888f85
+# GNU General Public License for more details.
888f85
+#
888f85
+# You should have received a copy of the GNU General Public License along
888f85
+# with this program.  If not, see <http://www.gnu.org/licenses/>.
888f85
+#
888f85
+# Author(s): Will Woods <wwoods@redhat.com>
888f85
+
888f85
+"""system_upgrade.py - DNF plugin to handle major-version system upgrades."""
888f85
+
888f85
+from subprocess import call, Popen, check_output, CalledProcessError
888f85
+import json
888f85
+import os
888f85
+import os.path
888f85
+import re
888f85
+import sys
888f85
+import uuid
888f85
+
888f85
+from systemd import journal
888f85
+
888f85
+from dnfpluginscore import _, logger
888f85
+
888f85
+import dnf
888f85
+import dnf.cli
888f85
+from dnf.cli import CliError
888f85
+from dnf.i18n import ucd
888f85
+import dnf.transaction
888f85
+from dnf.transaction_sr import serialize_transaction, TransactionReplay
888f85
+
888f85
+import libdnf.conf
888f85
+
888f85
+
888f85
+# Translators: This string is only used in unit tests.
888f85
+_("the color of the sky")
888f85
+
888f85
+DOWNLOAD_FINISHED_ID = uuid.UUID('9348174c5cc74001a71ef26bd79d302e')
888f85
+REBOOT_REQUESTED_ID = uuid.UUID('fef1cc509d5047268b83a3a553f54b43')
888f85
+UPGRADE_STARTED_ID = uuid.UUID('3e0a5636d16b4ca4bbe5321d06c6aa62')
888f85
+UPGRADE_FINISHED_ID = uuid.UUID('8cec00a1566f4d3594f116450395f06c')
888f85
+
888f85
+ID_TO_IDENTIFY_BOOTS = UPGRADE_STARTED_ID
888f85
+
888f85
+PLYMOUTH = '/usr/bin/plymouth'
888f85
+
888f85
+RELEASEVER_MSG = _(
888f85
+    "Need a --releasever greater than the current system version.")
888f85
+DOWNLOAD_FINISHED_MSG = _(  # Translators: do not change "reboot" here
888f85
+    "Download complete! Use 'dnf {command} reboot' to start the upgrade.\n"
888f85
+    "To remove cached metadata and transaction use 'dnf {command} clean'")
888f85
+CANT_RESET_RELEASEVER = _(
888f85
+    "Sorry, you need to use 'download --releasever' instead of '--network'")
888f85
+
888f85
+STATE_VERSION = 2
888f85
+
888f85
+# --- Miscellaneous helper functions ------------------------------------------
888f85
+
888f85
+
888f85
+def reboot():
888f85
+    if os.getenv("DNF_SYSTEM_UPGRADE_NO_REBOOT", default=False):
888f85
+        logger.info(_("Reboot turned off, not rebooting."))
888f85
+    else:
888f85
+        Popen(["systemctl", "reboot"])
888f85
+
888f85
+
888f85
+def get_url_from_os_release():
888f85
+    key = "UPGRADE_GUIDE_URL="
888f85
+    for path in ["/etc/os-release", "/usr/lib/os-release"]:
888f85
+        try:
888f85
+            with open(path) as release_file:
888f85
+                for line in release_file:
888f85
+                    line = line.strip()
888f85
+                    if line.startswith(key):
888f85
+                        return line[len(key):].strip('"')
888f85
+        except IOError:
888f85
+            continue
888f85
+    return None
888f85
+
888f85
+
888f85
+# DNF-FIXME: dnf.util.clear_dir() doesn't delete regular files :/
888f85
+def clear_dir(path, ignore=[]):
888f85
+    if not os.path.isdir(path):
888f85
+        return
888f85
+
888f85
+    for entry in os.listdir(path):
888f85
+        fullpath = os.path.join(path, entry)
888f85
+        if fullpath in ignore:
888f85
+            continue
888f85
+        try:
888f85
+            if os.path.isdir(fullpath):
888f85
+                dnf.util.rm_rf(fullpath)
888f85
+            else:
888f85
+                os.unlink(fullpath)
888f85
+        except OSError:
888f85
+            pass
888f85
+
888f85
+
888f85
+def check_release_ver(conf, target=None):
888f85
+    if dnf.rpm.detect_releasever(conf.installroot) == conf.releasever:
888f85
+        raise CliError(RELEASEVER_MSG)
888f85
+    if target and target != conf.releasever:
888f85
+        # it's too late to set releasever here, so this can't work.
888f85
+        # (see https://bugzilla.redhat.com/show_bug.cgi?id=1212341)
888f85
+        raise CliError(CANT_RESET_RELEASEVER)
888f85
+
888f85
+
888f85
+def disable_blanking():
888f85
+    try:
888f85
+        tty = open('/dev/tty0', 'wb')
888f85
+        tty.write(b'\33[9;0]')
888f85
+    except Exception as e:
888f85
+        print(_("Screen blanking can't be disabled: %s") % e)
888f85
+
888f85
+# --- State object - for tracking upgrade state between runs ------------------
888f85
+
888f85
+
888f85
+# DNF-INTEGRATION-NOTE: basically the same thing as dnf.persistor.JSONDB
888f85
+class State(object):
888f85
+    def __init__(self, statefile):
888f85
+        self.statefile = statefile
888f85
+        self._data = {}
888f85
+        self._read()
888f85
+
888f85
+    def _read(self):
888f85
+        try:
888f85
+            with open(self.statefile) as fp:
888f85
+                self._data = json.load(fp)
888f85
+        except IOError:
888f85
+            self._data = {}
888f85
+        except ValueError:
888f85
+            self._data = {}
888f85
+            logger.warning(_("Failed loading state file: %s, continuing with "
888f85
+                             "empty state."), self.statefile)
888f85
+
888f85
+    def write(self):
888f85
+        dnf.util.ensure_dir(os.path.dirname(self.statefile))
888f85
+        with open(self.statefile, 'w') as outf:
888f85
+            json.dump(self._data, outf, indent=4, sort_keys=True)
888f85
+
888f85
+    def clear(self):
888f85
+        if os.path.exists(self.statefile):
888f85
+            os.unlink(self.statefile)
888f85
+        self._read()
888f85
+
888f85
+    def __enter__(self):
888f85
+        return self
888f85
+
888f85
+    def __exit__(self, exc_type, exc_value, traceback):
888f85
+        if exc_type is None:
888f85
+            self.write()
888f85
+
888f85
+    # helper function for creating properties. pylint: disable=protected-access
888f85
+    def _prop(option):  # pylint: disable=no-self-argument
888f85
+        def setprop(self, value):
888f85
+            self._data[option] = value
888f85
+
888f85
+        def getprop(self):
888f85
+            return self._data.get(option)
888f85
+        return property(getprop, setprop)
888f85
+
888f85
+    #  !!! Increase STATE_VERSION for any changes in data structure like a new property or a new
888f85
+    #  data structure !!!
888f85
+    state_version = _prop("state_version")
888f85
+    download_status = _prop("download_status")
888f85
+    destdir = _prop("destdir")
888f85
+    target_releasever = _prop("target_releasever")
888f85
+    system_releasever = _prop("system_releasever")
888f85
+    gpgcheck = _prop("gpgcheck")
888f85
+    # list of repos with gpgcheck=True
888f85
+    gpgcheck_repos = _prop("gpgcheck_repos")
888f85
+    # list of repos with repo_gpgcheck=True
888f85
+    repo_gpgcheck_repos = _prop("repo_gpgcheck_repos")
888f85
+    upgrade_status = _prop("upgrade_status")
888f85
+    upgrade_command = _prop("upgrade_command")
888f85
+    distro_sync = _prop("distro_sync")
888f85
+    enable_disable_repos = _prop("enable_disable_repos")
888f85
+    module_platform_id = _prop("module_platform_id")
888f85
+
888f85
+# --- Plymouth output helpers -------------------------------------------------
888f85
+
888f85
+
888f85
+class PlymouthOutput(object):
888f85
+    """A plymouth output helper class.
888f85
+
888f85
+    Filters duplicate calls, and stops calling the plymouth binary if we
888f85
+    fail to contact it.
888f85
+    """
888f85
+
888f85
+    def __init__(self):
888f85
+        self.alive = True
888f85
+        self._last_args = dict()
888f85
+        self._last_msg = None
888f85
+
888f85
+    def _plymouth(self, cmd, *args):
888f85
+        dupe_cmd = (args == self._last_args.get(cmd))
888f85
+        if (self.alive and not dupe_cmd) or cmd == '--ping':
888f85
+            try:
888f85
+                self.alive = (call((PLYMOUTH, cmd) + args) == 0)
888f85
+            except OSError:
888f85
+                self.alive = False
888f85
+            self._last_args[cmd] = args
888f85
+        return self.alive
888f85
+
888f85
+    def ping(self):
888f85
+        return self._plymouth("--ping")
888f85
+
888f85
+    def message(self, msg):
888f85
+        if self._last_msg and self._last_msg != msg:
888f85
+            self._plymouth("hide-message", "--text", self._last_msg)
888f85
+        self._last_msg = msg
888f85
+        return self._plymouth("display-message", "--text", msg)
888f85
+
888f85
+    def set_mode(self):
888f85
+        mode = 'updates'
888f85
+        try:
888f85
+            s = check_output([PLYMOUTH, '--help'])
888f85
+            if re.search('--system-upgrade', ucd(s)):
888f85
+                mode = 'system-upgrade'
888f85
+        except (CalledProcessError, OSError):
888f85
+            pass
888f85
+        return self._plymouth("change-mode", "--" + mode)
888f85
+
888f85
+    def progress(self, percent):
888f85
+        return self._plymouth("system-update", "--progress", str(percent))
888f85
+
888f85
+
888f85
+# A single PlymouthOutput instance for us to use within this module
888f85
+Plymouth = PlymouthOutput()
888f85
+
888f85
+
888f85
+# A TransactionProgress class that updates plymouth for us.
888f85
+class PlymouthTransactionProgress(dnf.callback.TransactionProgress):
888f85
+
888f85
+    # pylint: disable=too-many-arguments
888f85
+    def progress(self, package, action, ti_done, ti_total, ts_done, ts_total):
888f85
+        self._update_plymouth(package, action, ts_done, ts_total)
888f85
+
888f85
+    def _update_plymouth(self, package, action, current, total):
888f85
+        # Prevents quick jumps of progressbar when pretrans scriptlets
888f85
+        # and TRANS_PREPARATION are reported as 1/1
888f85
+        if total == 1:
888f85
+            return
888f85
+        # Verification goes through all the packages again,
888f85
+        # which resets the "current" param value, this prevents
888f85
+        # resetting of the progress bar as well. (Rhbug:1809096)
888f85
+        if action != dnf.callback.PKG_VERIFY:
888f85
+            Plymouth.progress(int(90.0 * current / total))
888f85
+        else:
888f85
+            Plymouth.progress(90 + int(10.0 * current / total))
888f85
+
888f85
+        Plymouth.message(self._fmt_event(package, action, current, total))
888f85
+
888f85
+    def _fmt_event(self, package, action, current, total):
888f85
+        action = dnf.transaction.ACTIONS.get(action, action)
888f85
+        return "[%d/%d] %s %s..." % (current, total, action, package)
888f85
+
888f85
+# --- journal helpers -------------------------------------------------
888f85
+
888f85
+
888f85
+def find_boots(message_id):
888f85
+    """Find all boots with this message id.
888f85
+
888f85
+    Returns the entries of all found boots.
888f85
+    """
888f85
+    j = journal.Reader()
888f85
+    j.add_match(MESSAGE_ID=message_id.hex,  # identify the message
888f85
+                _UID=0)                     # prevent spoofing of logs
888f85
+
888f85
+    oldboot = None
888f85
+    for entry in j:
888f85
+        boot = entry['_BOOT_ID']
888f85
+        if boot == oldboot:
888f85
+            continue
888f85
+        oldboot = boot
888f85
+        yield entry
888f85
+
888f85
+
888f85
+def list_logs():
888f85
+    print(_('The following boots appear to contain upgrade logs:'))
888f85
+    n = -1
888f85
+    for n, entry in enumerate(find_boots(ID_TO_IDENTIFY_BOOTS)):
888f85
+        print('{} / {.hex}: {:%Y-%m-%d %H:%M:%S} {}→{}'.format(
888f85
+            n + 1,
888f85
+            entry['_BOOT_ID'],
888f85
+            entry['__REALTIME_TIMESTAMP'],
888f85
+            entry.get('SYSTEM_RELEASEVER', '??'),
888f85
+            entry.get('TARGET_RELEASEVER', '??')))
888f85
+    if n == -1:
888f85
+        print(_('-- no logs were found --'))
888f85
+
888f85
+
888f85
+def pick_boot(message_id, n):
888f85
+    boots = list(find_boots(message_id))
888f85
+    # Positive indices index all found boots starting with 1 and going forward,
888f85
+    # zero is the current boot, and -1, -2, -3 are previous going backwards.
888f85
+    # This is the same as journalctl.
888f85
+    try:
888f85
+        if n == 0:
888f85
+            raise IndexError
888f85
+        if n > 0:
888f85
+            n -= 1
888f85
+        return boots[n]['_BOOT_ID']
888f85
+    except IndexError:
888f85
+        raise CliError(_("Cannot find logs with this index."))
888f85
+
888f85
+
888f85
+def show_log(n):
888f85
+    boot_id = pick_boot(ID_TO_IDENTIFY_BOOTS, n)
888f85
+    process = Popen(['journalctl', '--boot', boot_id.hex])
888f85
+    process.wait()
888f85
+    rc = process.returncode
888f85
+    if rc == 1:
888f85
+        raise dnf.exceptions.Error(_("Unable to match systemd journal entry"))
888f85
+
888f85
+
888f85
+CMDS = ['download', 'clean', 'reboot', 'upgrade', 'log']
888f85
+
888f85
+# --- The actual Plugin and Command objects! ----------------------------------
888f85
+
888f85
+
888f85
+class SystemUpgradePlugin(dnf.Plugin):
888f85
+    name = 'system-upgrade'
888f85
+
888f85
+    def __init__(self, base, cli):
888f85
+        super(SystemUpgradePlugin, self).__init__(base, cli)
888f85
+        if cli:
888f85
+            cli.register_command(SystemUpgradeCommand)
888f85
+            cli.register_command(OfflineUpgradeCommand)
888f85
+            cli.register_command(OfflineDistrosyncCommand)
888f85
+
888f85
+
888f85
+class SystemUpgradeCommand(dnf.cli.Command):
888f85
+    aliases = ('system-upgrade', 'fedup',)
888f85
+    summary = _("Prepare system for upgrade to a new release")
888f85
+
888f85
+    DATADIR = 'var/lib/dnf/system-upgrade'
888f85
+
888f85
+    def __init__(self, cli):
888f85
+        super(SystemUpgradeCommand, self).__init__(cli)
888f85
+        self.datadir = os.path.join(cli.base.conf.installroot, self.DATADIR)
888f85
+        self.transaction_file = os.path.join(self.datadir, 'system-upgrade-transaction.json')
888f85
+        self.magic_symlink = os.path.join(cli.base.conf.installroot, 'system-update')
888f85
+
888f85
+        self.state = State(os.path.join(self.datadir, 'system-upgrade-state.json'))
888f85
+
888f85
+    @staticmethod
888f85
+    def set_argparser(parser):
888f85
+        parser.add_argument("--no-downgrade", dest='distro_sync',
888f85
+                            action='store_false',
888f85
+                            help=_("keep installed packages if the new "
888f85
+                                   "release's version is older"))
888f85
+        parser.add_argument('tid', nargs=1, choices=CMDS,
888f85
+                            metavar="[%s]" % "|".join(CMDS))
888f85
+        parser.add_argument('--number', type=int, help=_('which logs to show'))
888f85
+
888f85
+    def log_status(self, message, message_id):
888f85
+        """Log directly to the journal."""
888f85
+        journal.send(message,
888f85
+                     MESSAGE_ID=message_id,
888f85
+                     PRIORITY=journal.LOG_NOTICE,
888f85
+                     SYSTEM_RELEASEVER=self.state.system_releasever,
888f85
+                     TARGET_RELEASEVER=self.state.target_releasever,
888f85
+                     DNF_VERSION=dnf.const.VERSION)
888f85
+
888f85
+    def pre_configure(self):
888f85
+        self._call_sub("check")
888f85
+        self._call_sub("pre_configure")
888f85
+
888f85
+    def configure(self):
888f85
+        self._call_sub("configure")
888f85
+
888f85
+    def run(self):
888f85
+        self._call_sub("run")
888f85
+
888f85
+    def run_transaction(self):
888f85
+        self._call_sub("transaction")
888f85
+
888f85
+    def run_resolved(self):
888f85
+        self._call_sub("resolved")
888f85
+
888f85
+    def _call_sub(self, name):
888f85
+        subfunc = getattr(self, name + '_' + self.opts.tid[0], None)
888f85
+        if callable(subfunc):
888f85
+            subfunc()
888f85
+
888f85
+    def _check_state_version(self, command):
888f85
+        if self.state.state_version != STATE_VERSION:
888f85
+            msg = _("Incompatible version of data. Rerun 'dnf {command} download [OPTIONS]'"
888f85
+                    "").format(command=command)
888f85
+            raise CliError(msg)
888f85
+
888f85
+    def _set_cachedir(self):
888f85
+        # set download directories from json state file
888f85
+        self.base.conf.cachedir = self.datadir
888f85
+        self.base.conf.destdir = self.state.destdir if self.state.destdir else None
888f85
+
888f85
+    def _get_forward_reverse_pkg_reason_pairs(self):
888f85
+        """
888f85
+        forward = {repoid:{pkg_nevra: {tsi.action: tsi.reason}}
888f85
+        reverse = {pkg_nevra: {tsi.action: tsi.reason}}
888f85
+        :return: forward, reverse
888f85
+        """
888f85
+        backward_action = set(dnf.transaction.BACKWARD_ACTIONS + [libdnf.transaction.TransactionItemAction_REINSTALLED])
888f85
+        forward_actions = set(dnf.transaction.FORWARD_ACTIONS)
888f85
+
888f85
+        forward = {}
888f85
+        reverse = {}
888f85
+        for tsi in self.cli.base.transaction:
888f85
+            if tsi.action in forward_actions:
888f85
+                pkg = tsi.pkg
888f85
+                forward.setdefault(pkg.repo.id, {}).setdefault(
888f85
+                    str(pkg), {})[tsi.action] = tsi.reason
888f85
+            elif tsi.action in backward_action:
888f85
+                reverse.setdefault(str(tsi.pkg), {})[tsi.action] = tsi.reason
888f85
+        return forward, reverse
888f85
+
888f85
+    # == pre_configure_*: set up action-specific demands ==========================
888f85
+    def pre_configure_download(self):
888f85
+        # only download subcommand accepts --destdir command line option
888f85
+        self.base.conf.cachedir = self.datadir
888f85
+        self.base.conf.destdir = self.opts.destdir if self.opts.destdir else None
888f85
+        if 'offline-distrosync' == self.opts.command and not self.opts.distro_sync:
888f85
+            raise CliError(
888f85
+                _("Command 'offline-distrosync' cannot be used with --no-downgrade option"))
888f85
+        elif 'offline-upgrade' == self.opts.command:
888f85
+            self.opts.distro_sync = False
888f85
+
888f85
+    def pre_configure_reboot(self):
888f85
+        self._set_cachedir()
888f85
+
888f85
+    def pre_configure_upgrade(self):
888f85
+        self._set_cachedir()
888f85
+        if self.state.enable_disable_repos:
888f85
+            self.opts.repos_ed = self.state.enable_disable_repos
888f85
+        self.base.conf.releasever = self.state.target_releasever
888f85
+
888f85
+    def pre_configure_clean(self):
888f85
+        self._set_cachedir()
888f85
+
888f85
+    # == configure_*: set up action-specific demands ==========================
888f85
+
888f85
+    def configure_download(self):
888f85
+        if 'system-upgrade' == self.opts.command or 'fedup' == self.opts.command:
888f85
+            help_url = get_url_from_os_release()
888f85
+            if help_url:
888f85
+                msg = _('Additional information for System Upgrade: {}')
888f85
+                logger.info(msg.format(ucd(help_url)))
888f85
+            if self.base._promptWanted():
888f85
+                msg = _('Before you continue ensure that your system is fully upgraded by running '
888f85
+                        '"dnf --refresh upgrade". Do you want to continue')
888f85
+                if self.base.conf.assumeno or not self.base.output.userconfirm(
888f85
+                        msg='{} [y/N]: '.format(msg), defaultyes_msg='{} [Y/n]: '.format(msg)):
888f85
+                    logger.error(_("Operation aborted."))
888f85
+                    sys.exit(1)
888f85
+            check_release_ver(self.base.conf, target=self.opts.releasever)
888f85
+        self.cli.demands.root_user = True
888f85
+        self.cli.demands.resolving = True
888f85
+        self.cli.demands.available_repos = True
888f85
+        self.cli.demands.sack_activation = True
888f85
+        self.cli.demands.freshest_metadata = True
888f85
+        # We want to do the depsolve / download / transaction-test, but *not*
888f85
+        # run the actual RPM transaction to install the downloaded packages.
888f85
+        # Setting the "test" flag makes the RPM transaction a test transaction,
888f85
+        # so nothing actually gets installed.
888f85
+        # (It also means that we run two test transactions in a row, which is
888f85
+        # kind of silly, but that's something for DNF to fix...)
888f85
+        self.base.conf.tsflags += ["test"]
888f85
+
888f85
+    def configure_reboot(self):
888f85
+        # FUTURE: add a --debug-shell option to enable debug shell:
888f85
+        # systemctl add-wants system-update.target debug-shell.service
888f85
+        self.cli.demands.root_user = True
888f85
+
888f85
+    def configure_upgrade(self):
888f85
+        # same as the download, but offline and non-interactive. so...
888f85
+        self.cli.demands.root_user = True
888f85
+        self.cli.demands.resolving = True
888f85
+        self.cli.demands.available_repos = True
888f85
+        self.cli.demands.sack_activation = True
888f85
+        # use the saved value for --allowerasing, etc.
888f85
+        self.opts.distro_sync = self.state.distro_sync
888f85
+        if self.state.gpgcheck is not None:
888f85
+            self.base.conf.gpgcheck = self.state.gpgcheck
888f85
+        if self.state.gpgcheck_repos is not None:
888f85
+            for repo in self.base.repos.values():
888f85
+                repo.gpgcheck = repo.id in self.state.gpgcheck_repos
888f85
+        if self.state.repo_gpgcheck_repos is not None:
888f85
+            for repo in self.base.repos.values():
888f85
+                repo.repo_gpgcheck = repo.id in self.state.repo_gpgcheck_repos
888f85
+        self.base.conf.module_platform_id = self.state.module_platform_id
888f85
+        # don't try to get new metadata, 'cuz we're offline
888f85
+        self.cli.demands.cacheonly = True
888f85
+        # and don't ask any questions (we confirmed all this beforehand)
888f85
+        self.base.conf.assumeyes = True
888f85
+        self.cli.demands.transaction_display = PlymouthTransactionProgress()
888f85
+        # upgrade operation already removes all element that must be removed. Additional removal
888f85
+        # could trigger unwanted changes in transaction.
888f85
+        self.base.conf.clean_requirements_on_remove = False
888f85
+        self.base.conf.install_weak_deps = False
888f85
+
888f85
+    def configure_clean(self):
888f85
+        self.cli.demands.root_user = True
888f85
+
888f85
+    def configure_log(self):
888f85
+        pass
888f85
+
888f85
+    # == check_*: do any action-specific checks ===============================
888f85
+
888f85
+    def check_reboot(self):
888f85
+        if not self.state.download_status == 'complete':
888f85
+            raise CliError(_("system is not ready for upgrade"))
888f85
+        self._check_state_version(self.opts.command)
888f85
+        if self.state.upgrade_command != self.opts.command:
888f85
+            msg = _("the transaction was not prepared for '{command}'. "
888f85
+                    "Rerun 'dnf {command} download [OPTIONS]'").format(command=self.opts.command)
888f85
+            raise CliError(msg)
888f85
+        if os.path.lexists(self.magic_symlink):
888f85
+            raise CliError(_("upgrade is already scheduled"))
888f85
+        dnf.util.ensure_dir(self.datadir)
888f85
+        # FUTURE: checkRPMDBStatus(self.state.download_transaction_id)
888f85
+
888f85
+    def check_upgrade(self):
888f85
+        if not os.path.lexists(self.magic_symlink):
888f85
+            logger.info(_("trigger file does not exist. exiting quietly."))
888f85
+            raise SystemExit(0)
888f85
+        if os.readlink(self.magic_symlink) != self.datadir:
888f85
+            logger.info(_("another upgrade tool is running. exiting quietly."))
888f85
+            raise SystemExit(0)
888f85
+        # Delete symlink ASAP to avoid reboot loops
888f85
+        dnf.yum.misc.unlink_f(self.magic_symlink)
888f85
+        command = self.state.upgrade_command
888f85
+        if not command:
888f85
+            command = self.opts.command
888f85
+        self._check_state_version(command)
888f85
+        if not self.state.upgrade_status == 'ready':
888f85
+            msg = _("use 'dnf {command} reboot' to begin the upgrade").format(command=command)
888f85
+            raise CliError(msg)
888f85
+
888f85
+    # == run_*: run the action/prep the transaction ===========================
888f85
+
888f85
+    def run_prepare(self):
888f85
+        # make the magic symlink
888f85
+        os.symlink(self.datadir, self.magic_symlink)
888f85
+        # set upgrade_status so that the upgrade can run
888f85
+        with self.state as state:
888f85
+            state.upgrade_status = 'ready'
888f85
+
888f85
+    def run_reboot(self):
888f85
+        self.run_prepare()
888f85
+
888f85
+        if not self.opts.tid[0] == "reboot":
888f85
+            return
888f85
+
888f85
+        self.log_status(_("Rebooting to perform upgrade."),
888f85
+                        REBOOT_REQUESTED_ID)
888f85
+        reboot()
888f85
+
888f85
+    def run_download(self):
888f85
+        # Mark everything in the world for upgrade/sync
888f85
+        if self.opts.distro_sync:
888f85
+            self.base.distro_sync()
888f85
+        else:
888f85
+            self.base.upgrade_all()
888f85
+
888f85
+        if self.opts.command not in ['offline-upgrade', 'offline-distrosync']:
888f85
+            # Mark all installed groups and environments for upgrade
888f85
+            self.base.read_comps()
888f85
+            installed_groups = [g.id for g in self.base.comps.groups if self.base.history.group.get(g.id)]
888f85
+            if installed_groups:
888f85
+                self.base.env_group_upgrade(installed_groups)
888f85
+            installed_environments = [g.id for g in self.base.comps.environments if self.base.history.env.get(g.id)]
888f85
+            if installed_environments:
888f85
+                self.base.env_group_upgrade(installed_environments)
888f85
+
888f85
+        with self.state as state:
888f85
+            state.download_status = 'downloading'
888f85
+            state.target_releasever = self.base.conf.releasever
888f85
+            state.destdir = self.base.conf.destdir
888f85
+
888f85
+    def run_upgrade(self):
888f85
+        # change the upgrade status (so we can detect crashed upgrades later)
888f85
+        command = ''
888f85
+        with self.state as state:
888f85
+            state.upgrade_status = 'incomplete'
888f85
+            command = state.upgrade_command
888f85
+        if command == 'offline-upgrade':
888f85
+            msg = _("Starting offline upgrade. This will take a while.")
888f85
+        elif command == 'offline-distrosync':
888f85
+            msg = _("Starting offline distrosync. This will take a while.")
888f85
+        else:
888f85
+            msg = _("Starting system upgrade. This will take a while.")
888f85
+
888f85
+        self.log_status(msg, UPGRADE_STARTED_ID)
888f85
+
888f85
+        # reset the splash mode and let the user know we're running
888f85
+        Plymouth.set_mode()
888f85
+        Plymouth.progress(0)
888f85
+        Plymouth.message(msg)
888f85
+
888f85
+        # disable screen blanking
888f85
+        disable_blanking()
888f85
+
888f85
+        self.replay = TransactionReplay(self.base, self.transaction_file)
888f85
+        self.replay.run()
888f85
+
888f85
+    def run_clean(self):
888f85
+        logger.info(_("Cleaning up downloaded data..."))
888f85
+        # Don't delete persistor, it contains paths for downloaded packages
888f85
+        # that are used by dnf during finalizing base to clean them up
888f85
+        clear_dir(self.base.conf.cachedir,
888f85
+                  [dnf.persistor.TempfilePersistor(self.base.conf.cachedir).db_path])
888f85
+        with self.state as state:
888f85
+            state.download_status = None
888f85
+            state.state_version = None
888f85
+            state.upgrade_status = None
888f85
+            state.upgrade_command = None
888f85
+            state.destdir = None
888f85
+
888f85
+    def run_log(self):
888f85
+        if self.opts.number:
888f85
+            show_log(self.opts.number)
888f85
+        else:
888f85
+            list_logs()
888f85
+
888f85
+    # == resolved_*: do staff after succesful resolvement =====================
888f85
+
888f85
+    def resolved_upgrade(self):
888f85
+        """Adjust transaction reasons according to stored values"""
888f85
+        self.replay.post_transaction()
888f85
+
888f85
+    # == transaction_*: do stuff after a successful transaction ===============
888f85
+
888f85
+    def transaction_download(self):
888f85
+        transaction = self.base.history.get_current()
888f85
+
888f85
+        if not transaction.packages():
888f85
+            logger.info(_("The system-upgrade transaction is empty, your system is already up-to-date."))
888f85
+            return
888f85
+
888f85
+        data = serialize_transaction(transaction)
888f85
+        try:
888f85
+            with open(self.transaction_file, "w") as f:
888f85
+                json.dump(data, f, indent=4, sort_keys=True)
888f85
+                f.write("\n")
888f85
+
888f85
+            print(_("Transaction saved to {}.").format(self.transaction_file))
888f85
+
888f85
+        except OSError as e:
888f85
+            raise dnf.cli.CliError(_('Error storing transaction: {}').format(str(e)))
888f85
+
888f85
+        # Okay! Write out the state so the upgrade can use it.
888f85
+        system_ver = dnf.rpm.detect_releasever(self.base.conf.installroot)
888f85
+        with self.state as state:
888f85
+            state.download_status = 'complete'
888f85
+            state.state_version = STATE_VERSION
888f85
+            state.distro_sync = self.opts.distro_sync
888f85
+            state.gpgcheck = self.base.conf.gpgcheck
888f85
+            state.gpgcheck_repos = [
888f85
+                repo.id for repo in self.base.repos.values() if repo.gpgcheck]
888f85
+            state.repo_gpgcheck_repos = [
888f85
+                repo.id for repo in self.base.repos.values() if repo.repo_gpgcheck]
888f85
+            state.system_releasever = system_ver
888f85
+            state.target_releasever = self.base.conf.releasever
888f85
+            state.module_platform_id = self.base.conf.module_platform_id
888f85
+            state.enable_disable_repos = self.opts.repos_ed
888f85
+            state.destdir = self.base.conf.destdir
888f85
+            state.upgrade_command = self.opts.command
888f85
+
888f85
+        msg = DOWNLOAD_FINISHED_MSG.format(command=self.opts.command)
888f85
+        logger.info(msg)
888f85
+        self.log_status(_("Download finished."), DOWNLOAD_FINISHED_ID)
888f85
+
888f85
+    def transaction_upgrade(self):
888f85
+        Plymouth.message(_("Upgrade complete! Cleaning up and rebooting..."))
888f85
+        self.log_status(_("Upgrade complete! Cleaning up and rebooting..."),
888f85
+                        UPGRADE_FINISHED_ID)
888f85
+        self.run_clean()
888f85
+        if self.opts.tid[0] == "upgrade":
888f85
+            reboot()
888f85
+
888f85
+
888f85
+class OfflineUpgradeCommand(SystemUpgradeCommand):
888f85
+    aliases = ('offline-upgrade',)
888f85
+    summary = _("Prepare offline upgrade of the system")
888f85
+
888f85
+
888f85
+class OfflineDistrosyncCommand(SystemUpgradeCommand):
888f85
+    aliases = ('offline-distrosync',)
888f85
+    summary = _("Prepare offline distrosync of the system")
888f85
diff --git a/tests/test_system_upgrade.py b/tests/test_system_upgrade.py
888f85
new file mode 100644
888f85
index 0000000..6ef4c21
888f85
--- /dev/null
888f85
+++ b/tests/test_system_upgrade.py
888f85
@@ -0,0 +1,502 @@
888f85
+# test_system_upgrade.py - unit tests for system-upgrade plugin
888f85
+
888f85
+import system_upgrade
888f85
+
888f85
+from system_upgrade import PLYMOUTH, CliError
888f85
+
888f85
+import os
888f85
+import tempfile
888f85
+import shutil
888f85
+import gettext
888f85
+
888f85
+from dnf.callback import (PKG_CLEANUP, PKG_DOWNGRADE, PKG_INSTALL,
888f85
+                          PKG_OBSOLETE, PKG_REINSTALL, PKG_REMOVE, PKG_UPGRADE,
888f85
+                          PKG_VERIFY, TRANS_POST)
888f85
+
888f85
+import unittest
888f85
+
888f85
+from tests.support import mock
888f85
+patch = mock.patch
888f85
+
888f85
+
888f85
+@patch('system_upgrade.call', return_value=0)
888f85
+class PlymouthTestCase(unittest.TestCase):
888f85
+    def setUp(self):
888f85
+        self.ply = system_upgrade.PlymouthOutput()
888f85
+        self.msg = "Hello, plymouth."
888f85
+        self.msg_args = (PLYMOUTH, "display-message", "--text", self.msg)
888f85
+
888f85
+    def test_ping(self, call):
888f85
+        self.ply.ping()
888f85
+        call.assert_called_once_with((PLYMOUTH, "--ping"))
888f85
+        self.assertTrue(self.ply.alive)
888f85
+
888f85
+    def test_ping_when_dead(self, call):
888f85
+        call.return_value = 1
888f85
+        self.ply.ping()
888f85
+        self.assertFalse(self.ply.alive)
888f85
+        call.return_value = 0
888f85
+        self.ply.ping()
888f85
+        self.assertEqual(call.call_count, 2)
888f85
+        self.assertTrue(self.ply.alive)
888f85
+
888f85
+    def test_message(self, call):
888f85
+        self.ply.message(self.msg)
888f85
+        call.assert_called_once_with(self.msg_args)
888f85
+
888f85
+    def test_hide_message(self, call):
888f85
+        messages = ("first", "middle", "BONUS", "last")
888f85
+        for m in messages:
888f85
+            self.ply.message(m)
888f85
+
888f85
+        def hidem(m):
888f85
+            return mock.call((PLYMOUTH, "hide-message", "--text", m))
888f85
+
888f85
+        def dispm(m):
888f85
+            return mock.call((PLYMOUTH, "display-message", "--text", m))
888f85
+        m1, m2, m3, m4 = messages
888f85
+        call.assert_has_calls([
888f85
+            dispm(m1),
888f85
+            hidem(m1), dispm(m2),
888f85
+            hidem(m2), dispm(m3),
888f85
+            hidem(m3), dispm(m4),
888f85
+        ])
888f85
+
888f85
+    def test_message_dupe(self, call):
888f85
+        self.ply.message(self.msg)
888f85
+        self.ply.message(self.msg)
888f85
+        call.assert_called_once_with(self.msg_args)
888f85
+
888f85
+    def test_message_dead(self, call):
888f85
+        call.return_value = 1
888f85
+        self.ply.message(self.msg)
888f85
+        self.assertFalse(self.ply.alive)
888f85
+        self.ply.message("not even gonna bother")
888f85
+        call.assert_called_once_with(self.msg_args)
888f85
+
888f85
+    def test_progress(self, call):
888f85
+        self.ply.progress(27)
888f85
+        call.assert_called_once_with(
888f85
+            (PLYMOUTH, "system-update", "--progress", str(27)))
888f85
+
888f85
+    @patch('system_upgrade.check_output',
888f85
+           return_value="this plymouth does support --system-upgrade mode")
888f85
+    def test_mode(self, check_output, call):
888f85
+        self.ply.set_mode()
888f85
+        call.assert_called_once_with((PLYMOUTH, "change-mode", "--system-upgrade"))
888f85
+
888f85
+    @patch('system_upgrade.check_output',
888f85
+           return_value="this plymouth doesn't support system-upgrade mode")
888f85
+    def test_mode_no_system_upgrade_plymouth(self, check_output, call):
888f85
+        self.ply.set_mode()
888f85
+        call.assert_called_once_with((PLYMOUTH, "change-mode", "--updates"))
888f85
+
888f85
+    def test_mode_no_plymouth(self, call):
888f85
+        call.side_effect = OSError(2, 'No such file or directory')
888f85
+        self.ply.set_mode()
888f85
+        self.assertFalse(self.ply.alive)
888f85
+
888f85
+
888f85
+@patch('system_upgrade.call', return_value=0)
888f85
+class PlymouthTransactionProgressTestCase(unittest.TestCase):
888f85
+    actions = (PKG_CLEANUP, PKG_DOWNGRADE, PKG_INSTALL, PKG_OBSOLETE,
888f85
+               PKG_REINSTALL, PKG_REMOVE, PKG_UPGRADE, PKG_VERIFY,
888f85
+               TRANS_POST)
888f85
+
888f85
+    # pylint: disable=protected-access
888f85
+    def setUp(self):
888f85
+        system_upgrade.Plymouth = system_upgrade.PlymouthOutput()
888f85
+        self.display = system_upgrade.PlymouthTransactionProgress()
888f85
+        self.pkg = "testpackage"
888f85
+
888f85
+    def test_display(self, call):
888f85
+        for action in self.actions:
888f85
+            self.display.progress(self.pkg, action, 0, 100, 1, 1000)
888f85
+            msg = self.display._fmt_event(self.pkg, action, 1, 1000)
888f85
+            # updating plymouth display means two plymouth calls
888f85
+            call.assert_has_calls([
888f85
+                mock.call((PLYMOUTH, "system-update", "--progress", "0")),
888f85
+                mock.call((PLYMOUTH, "display-message", "--text", msg))
888f85
+            ], any_order=True)
888f85
+
888f85
+    def test_filter_calls(self, call):
888f85
+        action = PKG_INSTALL
888f85
+        # first display update -> set percentage and text
888f85
+        self.display.progress(self.pkg, action, 0, 100, 1, 1000)
888f85
+        msg1 = self.display._fmt_event(self.pkg, action, 1, 1000)
888f85
+        call.assert_has_calls([
888f85
+            mock.call((PLYMOUTH, "system-update", "--progress", "0")),
888f85
+            mock.call((PLYMOUTH, "display-message", "--text", msg1)),
888f85
+        ])
888f85
+
888f85
+        # event progress on the same transaction item.
888f85
+        # no new calls to plymouth because the percentage and text don't change
888f85
+        for te_cur in range(1, 100):
888f85
+            self.display.progress(self.pkg, action, te_cur, 100, 1, 1000)
888f85
+        call.assert_has_calls([
888f85
+            mock.call((PLYMOUTH, "system-update", "--progress", "0")),
888f85
+            mock.call((PLYMOUTH, "display-message", "--text", msg1)),
888f85
+        ])
888f85
+
888f85
+        # new item: new message ("[2/1000] ..."), but percentage still 0..
888f85
+        self.display.progress(self.pkg, action, 0, 100, 2, 1000)
888f85
+        # old message hidden, new message displayed. no new percentage.
888f85
+        msg2 = self.display._fmt_event(self.pkg, action, 2, 1000)
888f85
+        call.assert_has_calls([
888f85
+            mock.call((PLYMOUTH, "system-update", "--progress", "0")),
888f85
+            mock.call((PLYMOUTH, "display-message", "--text", msg1)),
888f85
+            mock.call((PLYMOUTH, "hide-message", "--text", msg1)),
888f85
+            mock.call((PLYMOUTH, "display-message", "--text", msg2)),
888f85
+        ])
888f85
+
888f85
+
888f85
+TESTLANG = "zh_CN"
888f85
+TESTLANG_MO = "po/%s.mo" % TESTLANG
888f85
+
888f85
+
888f85
+@unittest.skipUnless(os.path.exists(TESTLANG_MO), "make %s first" %
888f85
+                     TESTLANG_MO)
888f85
+# @unittest.skip("There is no translation yet to system-upgrade")
888f85
+class I18NTestCaseBase(unittest.TestCase):
888f85
+    @classmethod
888f85
+    @unittest.skip("There is no translation yet to system-upgrade")
888f85
+    def setUpClass(cls):
888f85
+        cls.localedir = tempfile.mkdtemp(prefix='system_upgrade_test_i18n-')
888f85
+        cls.msgdir = os.path.join(cls.localedir, TESTLANG + "/LC_MESSAGES")
888f85
+        cls.msgfile = "dnf-plugins-extras" + ".mo"
888f85
+        os.makedirs(cls.msgdir)
888f85
+        shutil.copy2(TESTLANG_MO, os.path.join(cls.msgdir, cls.msgfile))
888f85
+
888f85
+    @classmethod
888f85
+    def tearDownClass(cls):
888f85
+        shutil.rmtree(cls.localedir)
888f85
+
888f85
+    def setUp(self):
888f85
+        self.t = gettext.translation("dnf-plugins-extras", self.localedir,
888f85
+                                     languages=[TESTLANG], fallback=True)
888f85
+        self.gettext = self.t.gettext
888f85
+
888f85
+
888f85
+class I18NTestCase(I18NTestCaseBase):
888f85
+    @unittest.skip("There is no translation yet to system-upgrade")
888f85
+    def test_selftest(self):
888f85
+        self.assertIn(self.msgfile, os.listdir(self.msgdir))
888f85
+        self.assertIn(TESTLANG, os.listdir(self.localedir))
888f85
+        t = gettext.translation("dnf-plugins-extras", self.localedir,
888f85
+                                languages=[TESTLANG], fallback=False)
888f85
+        info = t.info()
888f85
+        self.assertIn("language", info)
888f85
+        self.assertEqual(info["language"], TESTLANG.replace("_", "-"))
888f85
+
888f85
+    @unittest.skip("There is no translation yet to system-upgrade")
888f85
+    def test_fallback(self):
888f85
+        msg = "THIS STRING DOES NOT EXIST"
888f85
+        trans_msg = self.gettext(msg)
888f85
+        self.assertEqual(msg, trans_msg)
888f85
+
888f85
+    @unittest.skip("There is no translation yet to system-upgrade")
888f85
+    def test_translation(self):
888f85
+        msg = "the color of the sky"
888f85
+        trans_msg = self.gettext(msg)
888f85
+        self.assertNotEqual(msg, trans_msg)
888f85
+
888f85
+
888f85
+class StateTestCase(unittest.TestCase):
888f85
+    @classmethod
888f85
+    def setUpClass(cls):
888f85
+        cls.statedir = tempfile.mkdtemp(prefix="system_upgrade_test_state-")
888f85
+        cls.StateClass = system_upgrade.State
888f85
+
888f85
+    def setUp(self):
888f85
+        self.state = self.StateClass(os.path.join(self.statedir, "state"))
888f85
+
888f85
+    def test_bool_value(self):
888f85
+        with self.state:
888f85
+            self.state.distro_sync = True
888f85
+        del self.state
888f85
+        self.state = self.StateClass(os.path.join(self.statedir, "state"))
888f85
+        self.assertIs(self.state.distro_sync, True)
888f85
+
888f85
+    @classmethod
888f85
+    def tearDownClass(cls):
888f85
+        shutil.rmtree(cls.statedir)
888f85
+
888f85
+
888f85
+class UtilTestCase(unittest.TestCase):
888f85
+    def setUp(self):
888f85
+        self.tmpdir = tempfile.mkdtemp(prefix='system_upgrade_test_util-')
888f85
+        self.dirs = ["dir1", "dir2"]
888f85
+        self.files = ["file1", "dir2/file2"]
888f85
+        for d in self.dirs:
888f85
+            os.makedirs(os.path.join(self.tmpdir, d))
888f85
+        for f in self.files:
888f85
+            with open(os.path.join(self.tmpdir, f), 'wt') as fobj:
888f85
+                fobj.write("hi there\n")
888f85
+
888f85
+    def test_self_test(self):
888f85
+        for d in self.dirs:
888f85
+            self.assertTrue(os.path.isdir(os.path.join(self.tmpdir, d)))
888f85
+        for f in self.files:
888f85
+            self.assertTrue(os.path.exists(os.path.join(self.tmpdir, f)))
888f85
+
888f85
+    def test_clear_dir(self):
888f85
+        self.assertTrue(os.path.isdir(self.tmpdir))
888f85
+        system_upgrade.clear_dir(self.tmpdir)
888f85
+        self.assertTrue(os.path.isdir(self.tmpdir))
888f85
+        self.assertEqual(os.listdir(self.tmpdir), [])
888f85
+
888f85
+    def tearDown(self):
888f85
+        shutil.rmtree(self.tmpdir)
888f85
+
888f85
+
888f85
+class CommandTestCaseBase(unittest.TestCase):
888f85
+    def setUp(self):
888f85
+        self.datadir = tempfile.mkdtemp(prefix="system_upgrade_test_datadir-")
888f85
+        self.installroot = tempfile.TemporaryDirectory(prefix="system_upgrade_test_installroot-")
888f85
+        system_upgrade.SystemUpgradeCommand.DATADIR = self.datadir
888f85
+        self.cli = mock.MagicMock()
888f85
+        # the installroot is not strictly necessary for the test, but
888f85
+        # releasever detection is accessing host system files without it, and
888f85
+        # this fails on permissions in COPR srpm builds (e.g. from rpm-gitoverlay)
888f85
+        self.cli.base.conf.installroot = self.installroot.name
888f85
+        self.command = system_upgrade.SystemUpgradeCommand(cli=self.cli)
888f85
+        self.command.base.conf.cachedir = os.path.join(self.datadir, "cache")
888f85
+        self.command.base.conf.destdir = None
888f85
+
888f85
+    def tearDown(self):
888f85
+        shutil.rmtree(self.datadir)
888f85
+        self.installroot.cleanup()
888f85
+
888f85
+
888f85
+class CommandTestCase(CommandTestCaseBase):
888f85
+    # self-tests for the command test cases
888f85
+    def test_state(self):
888f85
+        # initial state: no status
888f85
+        self.assertIsNone(self.command.state.download_status)
888f85
+        self.assertIsNone(self.command.state.upgrade_status)
888f85
+
888f85
+
888f85
+class CleanCommandTestCase(CommandTestCaseBase):
888f85
+    def test_pre_configure_clean(self):
888f85
+        with self.command.state as state:
888f85
+            state.destdir = "/grape/wine"
888f85
+        self.command.pre_configure_clean()
888f85
+        self.assertEqual(self.command.base.conf.destdir, "/grape/wine")
888f85
+
888f85
+    def test_configure_clean(self):
888f85
+        self.cli.demands.root_user = None
888f85
+        self.command.configure_clean()
888f85
+        self.assertTrue(self.cli.demands.root_user)
888f85
+
888f85
+    def test_run_clean(self):
888f85
+        with self.command.state as state:
888f85
+            state.download_status = "complete"
888f85
+            state.upgrade_status = "ready"
888f85
+        # make sure the datadir and state info is set up OK
888f85
+        self.assertEqual(self.command.state.download_status, "complete")
888f85
+        self.assertEqual(self.command.state.upgrade_status, "ready")
888f85
+        # run cleanup
888f85
+        self.command.run_clean()
888f85
+        # state is cleared
888f85
+        self.assertIsNone(self.command.state.download_status)
888f85
+        self.assertIsNone(self.command.state.upgrade_status)
888f85
+
888f85
+
888f85
+class RebootCheckCommandTestCase(CommandTestCaseBase):
888f85
+    def setUp(self):
888f85
+        super(RebootCheckCommandTestCase, self).setUp()
888f85
+        self.magic_symlink = self.datadir + '/symlink'
888f85
+        self.command.magic_symlink = self.magic_symlink
888f85
+
888f85
+    def test_pre_configure_reboot(self):
888f85
+        with self.command.state as state:
888f85
+            state.destdir = "/grape/wine"
888f85
+        self.command.pre_configure_reboot()
888f85
+        self.assertEqual(self.command.base.conf.destdir, "/grape/wine")
888f85
+
888f85
+    def test_configure_reboot(self):
888f85
+        self.cli.demands.root_user = None
888f85
+        self.command.configure_reboot()
888f85
+        self.assertTrue(self.cli.demands.root_user)
888f85
+
888f85
+    def check_reboot(self, status='complete', lexists=False, command='system-upgrade',
888f85
+                     state_command='system-upgrade'):
888f85
+        with patch('system_upgrade.os.path.lexists') as lexists_func:
888f85
+            self.command.state.state_version = 2
888f85
+            self.command.state.download_status = status
888f85
+            self.command.opts = mock.MagicMock()
888f85
+            self.command.opts.command = command
888f85
+            self.command.state.upgrade_command = state_command
888f85
+            lexists_func.return_value = lexists
888f85
+            self.command.check_reboot()
888f85
+
888f85
+    def test_check_reboot_ok(self):
888f85
+        self.check_reboot(status='complete', lexists=False)
888f85
+
888f85
+    def test_check_reboot_different_command(self):
888f85
+        with self.assertRaises(CliError):
888f85
+            self.check_reboot(status='complete', lexists=False, command='system-upgrade',
888f85
+                              state_command='offline-upgrade')
888f85
+
888f85
+    def test_check_reboot_no_download(self):
888f85
+        with self.assertRaises(CliError):
888f85
+            self.check_reboot(status=None, lexists=False)
888f85
+
888f85
+    def test_check_reboot_link_exists(self):
888f85
+        with self.assertRaises(CliError):
888f85
+            self.check_reboot(status='complete', lexists=True)
888f85
+
888f85
+    def test_run_prepare(self):
888f85
+        self.command.run_prepare()
888f85
+        self.assertEqual(os.readlink(self.magic_symlink), self.datadir)
888f85
+        self.assertEqual(self.command.state.upgrade_status, 'ready')
888f85
+
888f85
+    @patch('system_upgrade.SystemUpgradeCommand.run_prepare')
888f85
+    @patch('system_upgrade.SystemUpgradeCommand.log_status')
888f85
+    @patch('system_upgrade.reboot')
888f85
+    def test_run_reboot(self, reboot, log_status, run_prepare):
888f85
+        self.command.opts = mock.MagicMock()
888f85
+        self.command.opts.tid = ["reboot"]
888f85
+        self.command.run_reboot()
888f85
+        run_prepare.assert_called_once_with()
888f85
+        self.assertEqual(system_upgrade.REBOOT_REQUESTED_ID,
888f85
+                         log_status.call_args[0][1])
888f85
+        self.assertTrue(reboot.called)
888f85
+
888f85
+    @patch('system_upgrade.SystemUpgradeCommand.run_prepare')
888f85
+    @patch('system_upgrade.SystemUpgradeCommand.log_status')
888f85
+    @patch('system_upgrade.reboot')
888f85
+    def test_reboot_prepare_only(self, reboot, log_status, run_prepare):
888f85
+        self.command.opts = mock.MagicMock()
888f85
+        self.command.opts.tid = [None]
888f85
+        self.command.run_reboot()
888f85
+        run_prepare.assert_called_once_with()
888f85
+        self.assertFalse(log_status.called)
888f85
+        self.assertFalse(reboot.called)
888f85
+
888f85
+
888f85
+class DownloadCommandTestCase(CommandTestCase):
888f85
+    def test_pre_configure_download_default(self):
888f85
+        self.command.opts = mock.MagicMock()
888f85
+        self.command.opts.destdir = None
888f85
+        self.command.base.conf.destdir = None
888f85
+        self.command.pre_configure_download()
888f85
+        self.assertEqual(self.command.base.conf.cachedir, self.datadir)
888f85
+
888f85
+    def test_pre_configure_download_destdir(self):
888f85
+        self.command.opts = mock.MagicMock()
888f85
+        self.command.opts.destdir = self.datadir
888f85
+        self.command.pre_configure_download()
888f85
+        self.assertEqual(self.command.base.conf.destdir, self.datadir)
888f85
+
888f85
+    def test_configure_download(self):
888f85
+        self.command.opts = mock.MagicMock()
888f85
+        self.command.opts.tid = "download"
888f85
+        self.command.configure()
888f85
+        self.assertTrue(self.cli.demands.root_user)
888f85
+        self.assertTrue(self.cli.demands.resolving)
888f85
+        self.assertTrue(self.cli.demands.sack_activation)
888f85
+        self.assertTrue(self.cli.demands.available_repos)
888f85
+
888f85
+    def test_transaction_download(self):
888f85
+        pkg = mock.MagicMock()
888f85
+        repo = mock.MagicMock()
888f85
+        repo.id = 'test'
888f85
+        pkg.name = "kernel"
888f85
+        pkg.repo = repo
888f85
+        self.cli.base.transaction.install_set = [pkg]
888f85
+        self.command.opts = mock.MagicMock()
888f85
+        self.command.opts.distro_sync = True
888f85
+        self.command.opts.command = "system_upgrade"
888f85
+        self.command.opts.repos_ed = []
888f85
+        self.cli.demands.allow_erasing = "allow_erasing"
888f85
+        self.command.base.conf.best = True
888f85
+        self.command.base.conf.releasever = "35"
888f85
+        self.command.base.conf.gpgcheck = True
888f85
+        self.command.opts.destdir = self.datadir
888f85
+        self.command.base.conf.install_weak_deps = True
888f85
+        self.command.base.conf.module_platform_id = ''
888f85
+        self.command.pre_configure_download()
888f85
+        self.command.transaction_download()
888f85
+        with system_upgrade.State(self.command.state.statefile) as state:
888f85
+            self.assertEqual(state.state_version, system_upgrade.STATE_VERSION)
888f85
+            self.assertEqual(state.download_status, "complete")
888f85
+            self.assertEqual(state.distro_sync, True)
888f85
+            self.assertEqual(state.destdir, self.datadir)
888f85
+            self.assertEqual(state.upgrade_command, "system_upgrade")
888f85
+
888f85
+    def test_transaction_download_offline_upgrade(self):
888f85
+        pkg = mock.MagicMock()
888f85
+        repo = mock.MagicMock()
888f85
+        repo.id = 'test'
888f85
+        pkg.name = "kernel"
888f85
+        pkg.repo = repo
888f85
+        self.cli.base.transaction.install_set = [pkg]
888f85
+        self.command.opts = mock.MagicMock()
888f85
+        self.command.opts.distro_sync = True
888f85
+        self.command.opts.command = "offline-upgrade"
888f85
+        self.command.opts.repos_ed = []
888f85
+        self.cli.demands.allow_erasing = "allow_erasing"
888f85
+        self.command.base.conf.best = True
888f85
+        self.command.base.conf.releasever = "35"
888f85
+        self.command.base.conf.gpgcheck = True
888f85
+        self.command.opts.destdir = self.datadir
888f85
+        self.command.base.conf.install_weak_deps = True
888f85
+        self.command.base.conf.module_platform_id = ''
888f85
+        self.command.pre_configure_download()
888f85
+        self.command.transaction_download()
888f85
+        with system_upgrade.State(self.command.state.statefile) as state:
888f85
+            self.assertEqual(state.download_status, "complete")
888f85
+            self.assertEqual(state.distro_sync, False)
888f85
+            self.assertEqual(state.destdir, self.datadir)
888f85
+            self.assertEqual(state.upgrade_command, "offline-upgrade")
888f85
+
888f85
+
888f85
+class UpgradeCommandTestCase(CommandTestCase):
888f85
+    def test_pre_configure_upgrade(self):
888f85
+        with self.command.state as state:
888f85
+            state.destdir = "/grape/wine"
888f85
+            state.target_releasever = "35"
888f85
+        self.command.pre_configure_upgrade()
888f85
+        self.assertEqual(self.command.base.conf.destdir, "/grape/wine")
888f85
+        self.assertEqual(self.command.base.conf.releasever, "35")
888f85
+
888f85
+    def test_configure_upgrade(self):
888f85
+        # write state like download would have
888f85
+        with self.command.state as state:
888f85
+            state.download_status = "complete"
888f85
+            state.distro_sync = True
888f85
+            state.allow_erasing = True
888f85
+            state.best = True
888f85
+        # okay, now configure upgrade
888f85
+        self.command.opts = mock.MagicMock()
888f85
+        self.command.opts.tid = "upgrade"
888f85
+        self.command.configure()
888f85
+        # did we reset the depsolving flags?
888f85
+        self.assertTrue(self.command.opts.distro_sync)
888f85
+        self.assertTrue(self.cli.demands.allow_erasing)
888f85
+        self.assertTrue(self.command.base.conf.best)
888f85
+        # are we on autopilot?
888f85
+        self.assertTrue(self.command.base.conf.assumeyes)
888f85
+        self.assertTrue(self.cli.demands.cacheonly)
888f85
+
888f85
+
888f85
+class LogCommandTestCase(CommandTestCase):
888f85
+    def test_configure_log(self):
888f85
+        self.command.opts = mock.MagicMock()
888f85
+        self.command.opts.tid = "log"
888f85
+        self.command.configure()
888f85
+
888f85
+    def test_run_log_list(self):
888f85
+        self.command.opts = mock.MagicMock()
888f85
+        self.command.opts.number = None
888f85
+        with patch('system_upgrade.list_logs') as list_logs:
888f85
+            self.command.run_log()
888f85
+        list_logs.assert_called_once_with()
888f85
+
888f85
+    def test_run_log_prev(self):
888f85
+        with patch('system_upgrade.show_log') as show_log:
888f85
+            self.command.opts = mock.MagicMock()
888f85
+            self.command.opts.number = -2
888f85
+            self.command.run_log()
888f85
+        show_log.assert_called_once_with(-2)
888f85
-- 
888f85
2.37.3
888f85