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

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