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

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