Blame SOURCES/0011-Add-new-command-modulesync-RhBug1868047.patch

0e2001
From 6ea94d9c768eb45975f314e11ab9dd88284fa380 Mon Sep 17 00:00:00 2001
0e2001
From: Jaroslav Mracek <jmracek@redhat.com>
0e2001
Date: Mon, 27 Sep 2021 11:29:01 +0200
0e2001
Subject: [PATCH] Add new command modulesync (RhBug:1868047)
0e2001
0e2001
It will download module metadata from all enabled repositories,
0e2001
module artifacts and profiles of matching modules. Then it creates
0e2001
a repository.
0e2001
0e2001
= changelog =
0e2001
msg:           Add a new subpackage with modulesync command. The command
0e2001
downloads packages from modules and/or creates a repository with modular
0e2001
data.
0e2001
type:          enhancement
0e2001
resolves:      https://bugzilla.redhat.com/show_bug.cgi?id=1868047
0e2001
---
0e2001
 dnf-plugins-core.spec  |  20 ++++++++++++++++++++
0e2001
 doc/CMakeLists.txt     |   1 +
0e2001
 doc/conf.py            |   1 +
0e2001
 doc/index.rst          |   1 +
0e2001
 doc/modulesync.rst     | 103 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
0e2001
 plugins/CMakeLists.txt |   1 +
0e2001
 plugins/modulesync.py  | 208 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
0e2001
 7 files changed, 335 insertions(+)
0e2001
 create mode 100644 doc/modulesync.rst
0e2001
 create mode 100644 plugins/modulesync.py
0e2001
0e2001
diff --git a/dnf-plugins-core.spec b/dnf-plugins-core.spec
0e2001
index cef836f..afdbcbb 100644
0e2001
--- a/dnf-plugins-core.spec
0e2001
+++ b/dnf-plugins-core.spec
0e2001
@@ -402,6 +402,19 @@ versions of those packages. This allows you to e.g. protect packages from being
0e2001
 updated by newer versions.
0e2001
 %endif
0e2001
 
0e2001
+%if %{with python3}
0e2001
+%package -n python3-dnf-plugin-modulesync
0e2001
+Summary:        Download module metadata and packages and create repository
0e2001
+Requires:       python3-%{name} = %{version}-%{release}
0e2001
+Requires:       createrepo_c >= 0.17.4
0e2001
+Provides:       dnf-plugin-modulesync =  %{version}-%{release}
0e2001
+Provides:       dnf-command(modulesync)
0e2001
+
0e2001
+%description -n python3-dnf-plugin-modulesync
0e2001
+Download module metadata from all enabled repositories, module artifacts and profiles of matching modules and create
0e2001
+repository.
0e2001
+%endif
0e2001
+
0e2001
 %prep
0e2001
 %autosetup
0e2001
 %if %{with python2}
0e2001
@@ -762,6 +775,13 @@ ln -sf %{_mandir}/man1/%{yum_utils_subpackage_name}.1.gz %{buildroot}%{_mandir}/
0e2001
 %endif
0e2001
 %endif
0e2001
 
0e2001
+%if %{with python3}
0e2001
+%files -n python3-dnf-plugin-modulesync
0e2001
+%{python3_sitelib}/dnf-plugins/modulesync.*
0e2001
+%{python3_sitelib}/dnf-plugins/__pycache__/modulesync.*
0e2001
+%{_mandir}/man8/dnf-modulesync.*
0e2001
+%endif
0e2001
+
0e2001
 %changelog
0e2001
 * Mon Apr 12 2021 Nicola Sella <nsella@redhat.com> - 4.0.21-1
0e2001
 - Add missing command line option to documentation
0e2001
diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt
0e2001
index 3fb665d..ff84cf8 100644
0e2001
--- a/doc/CMakeLists.txt
0e2001
+++ b/doc/CMakeLists.txt
0e2001
@@ -28,6 +28,7 @@ INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/dnf-builddep.8
0e2001
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-generate_completion_cache.8
0e2001
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-groups-manager.8
0e2001
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-leaves.8
0e2001
+    ${CMAKE_CURRENT_BINARY_DIR}/dnf-modulesync.8
0e2001
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-needs-restarting.8
0e2001
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-repoclosure.8
0e2001
     ${CMAKE_CURRENT_BINARY_DIR}/dnf-repodiff.8
0e2001
diff --git a/doc/conf.py b/doc/conf.py
0e2001
index 645185a..41d6936 100644
0e2001
--- a/doc/conf.py
0e2001
+++ b/doc/conf.py
0e2001
@@ -254,6 +254,7 @@ man_pages = [
0e2001
     ('groups-manager', 'dnf-groups-manager', u'DNF groups-manager Plugin', AUTHORS, 8),
0e2001
     ('leaves', 'dnf-leaves', u'DNF leaves Plugin', AUTHORS, 8),
0e2001
     ('local', 'dnf-local', u'DNF local Plugin', AUTHORS, 8),
0e2001
+    ('modulesync', 'dnf-modulesync', u'DNF modulesync Plugin', AUTHORS, 8),
0e2001
     ('needs_restarting', 'dnf-needs-restarting', u'DNF needs_restarting Plugin', AUTHORS, 8),
0e2001
     ('repoclosure', 'dnf-repoclosure', u'DNF repoclosure Plugin', AUTHORS, 8),
0e2001
     ('repodiff', 'dnf-repodiff', u'DNF repodiff Plugin', AUTHORS, 8),
0e2001
diff --git a/doc/index.rst b/doc/index.rst
0e2001
index 7213253..07f6052 100644
0e2001
--- a/doc/index.rst
0e2001
+++ b/doc/index.rst
0e2001
@@ -37,6 +37,7 @@ This documents core plugins of DNF:
0e2001
    leaves
0e2001
    local
0e2001
    migrate
0e2001
+   modulesync
0e2001
    needs_restarting
0e2001
    post-transaction-actions
0e2001
    repoclosure
0e2001
diff --git a/doc/modulesync.rst b/doc/modulesync.rst
0e2001
new file mode 100644
0e2001
index 0000000..2837287
0e2001
--- /dev/null
0e2001
+++ b/doc/modulesync.rst
0e2001
@@ -0,0 +1,103 @@
0e2001
+..
0e2001
+  Copyright (C) 2015  Red Hat, Inc.
0e2001
+
0e2001
+  This copyrighted material is made available to anyone wishing to use,
0e2001
+  modify, copy, or redistribute it subject to the terms and conditions of
0e2001
+  the GNU General Public License v.2, or (at your option) any later version.
0e2001
+  This program is distributed in the hope that it will be useful, but WITHOUT
0e2001
+  ANY WARRANTY expressed or implied, including the implied warranties of
0e2001
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
0e2001
+  Public License for more details.  You should have received a copy of the
0e2001
+  GNU General Public License along with this program; if not, write to the
0e2001
+  Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
0e2001
+  02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
0e2001
+  source code or documentation are not subject to the GNU General Public
0e2001
+  License and may only be used or replicated with the express permission of
0e2001
+  Red Hat, Inc.
0e2001
+
0e2001
+====================
0e2001
+DNF modulesync Plugin
0e2001
+====================
0e2001
+
0e2001
+Download packages from modules and/or create a repository with modular data.
0e2001
+
0e2001
+--------
0e2001
+Synopsis
0e2001
+--------
0e2001
+
0e2001
+``dnf modulesync [options] [<module-spec>...]``
0e2001
+
0e2001
+-----------
0e2001
+Description
0e2001
+-----------
0e2001
+
0e2001
+`modulesync` downloads packages from modules according to provided arguments and creates a repository with modular data
0e2001
+in working directory. In environment with modules it is recommend to use the command for redistribution of packages,
0e2001
+because DNF does not allow installation of modular packages without modular metadata on the system (Fail-safe
0e2001
+mechanism). The command without an argument creates a repository like `createrepo_c` but with modular metadata collected
0e2001
+from all available repositories.
0e2001
+
0e2001
+See examples.
0e2001
+
0e2001
+---------
0e2001
+Arguments
0e2001
+---------
0e2001
+
0e2001
+``<module-spec>``
0e2001
+    Module specification for the package to download. The argument is an optional.
0e2001
+
0e2001
+-------
0e2001
+Options
0e2001
+-------
0e2001
+
0e2001
+All general DNF options are accepted. Namely, the ``--destdir`` option can be used to specify directory where packages
0e2001
+will be downloaded and the new repository created. See `Options` in :manpage:`dnf(8)` for details.
0e2001
+
0e2001
+
0e2001
+``-n, --newest-only``
0e2001
+    Download only packages from the newest modules.
0e2001
+
0e2001
+``--enable_source_repos``
0e2001
+    Enable repositories with source packages
0e2001
+
0e2001
+``--enable_debug_repos``
0e2001
+    Enable repositories with debug-info and debug-source packages
0e2001
+
0e2001
+``--resolve``
0e2001
+    Resolve and download needed dependencies
0e2001
+
0e2001
+--------
0e2001
+Examples
0e2001
+--------
0e2001
+
0e2001
+``dnf modulesync nodejs``
0e2001
+    Download packages from `nodejs` module and crete a repository with modular metadata in working directory
0e2001
+
0e2001
+``dnf download nodejs``
0e2001
+
0e2001
+``dnf modulesync``
0e2001
+    The first `download` command downloads nodejs package into working directory. In environment with modules `nodejs`
0e2001
+    package can be a modular package therefore when I create a repository I have to insert also modular metadata
0e2001
+    from available repositories to ensure 100% functionality. Instead of `createrepo_c` use `dnf modulesync`
0e2001
+    to create a repository in working directory with nodejs package and modular metadata.
0e2001
+
0e2001
+``dnf --destdir=/tmp/my-temp modulesync nodejs:14/minimal --resolve``
0e2001
+    Download package required for installation of `minimal` profile from module `nodejs` and stream `14` into directory
0e2001
+    `/tmp/my-temp` and all required dependencies. Then it will create a repository in `/tmp/my-temp` directory with
0e2001
+    previously downloaded packages and modular metadata from all available repositories.
0e2001
+
0e2001
+``dnf module install nodejs:14/minimal --downloadonly --destdir=/tmp/my-temp``
0e2001
+
0e2001
+``dnf modulesync --destdir=/tmp/my-temp``
0e2001
+    The first `dnf module install` command downloads package from required for installation of `minimal` profile from module
0e2001
+    `nodejs` and stream `14` into directory `/tmp/my-temp`. The second command `dnf modulesync` will create
0e2001
+    a repository in `/tmp/my-temp` directory with previously downloaded packages and modular metadata from all
0e2001
+    available repositories. In comparison to `dnf --destdir=/tmp/my-temp modulesync nodejs:14/minimal --resolve` it will
0e2001
+    only download packages required for installation on current system.
0e2001
+
0e2001
+
0e2001
+--------
0e2001
+See Also
0e2001
+--------
0e2001
+
0e2001
+* :manpage:`dnf(8)`, DNF Command Reference
0e2001
diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt
0e2001
index f66d3df..59f148f 100644
0e2001
--- a/plugins/CMakeLists.txt
0e2001
+++ b/plugins/CMakeLists.txt
0e2001
@@ -22,6 +22,7 @@ INSTALL (FILES repograph.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
0e2001
 INSTALL (FILES repomanage.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
0e2001
 INSTALL (FILES reposync.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
0e2001
 INSTALL (FILES show_leaves.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
0e2001
+INSTALL (FILES modulesync.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
0e2001
 INSTALL (FILES versionlock.py DESTINATION ${PYTHON_INSTALL_DIR}/dnf-plugins)
0e2001
 
0e2001
 ADD_SUBDIRECTORY (dnfpluginscore)
0e2001
diff --git a/plugins/modulesync.py b/plugins/modulesync.py
0e2001
new file mode 100644
0e2001
index 0000000..c1c33e4
0e2001
--- /dev/null
0e2001
+++ b/plugins/modulesync.py
0e2001
@@ -0,0 +1,208 @@
0e2001
+# Copyright (C) 2021  Red Hat, Inc.
0e2001
+#
0e2001
+# This copyrighted material is made available to anyone wishing to use,
0e2001
+# modify, copy, or redistribute it subject to the terms and conditions of
0e2001
+# the GNU General Public License v.2, or (at your option) any later version.
0e2001
+# This program is distributed in the hope that it will be useful, but WITHOUT
0e2001
+# ANY WARRANTY expressed or implied, including the implied warranties of
0e2001
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
0e2001
+# Public License for more details.  You should have received a copy of the
0e2001
+# GNU General Public License along with this program; if not, write to the
0e2001
+# Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
0e2001
+# 02110-1301, USA.  Any Red Hat trademarks that are incorporated in the
0e2001
+# source code or documentation are not subject to the GNU General Public
0e2001
+# License and may only be used or replicated with the express permission of
0e2001
+# Red Hat, Inc.
0e2001
+#
0e2001
+
0e2001
+from __future__ import absolute_import
0e2001
+from __future__ import unicode_literals
0e2001
+from dnfpluginscore import _, P_, logger
0e2001
+from dnf.cli.option_parser import OptionParser
0e2001
+
0e2001
+import os
0e2001
+import shutil
0e2001
+import subprocess
0e2001
+
0e2001
+import dnf
0e2001
+import dnf.cli
0e2001
+import dnf.i18n
0e2001
+import hawkey
0e2001
+
0e2001
+
0e2001
+@dnf.plugin.register_command
0e2001
+class SyncToolCommand(dnf.cli.Command):
0e2001
+
0e2001
+    aliases = ['modulesync']
0e2001
+    summary = _('Download packages from modules and/or create a repository with modular data')
0e2001
+
0e2001
+    def __init__(self, cli):
0e2001
+        super(SyncToolCommand, self).__init__(cli)
0e2001
+
0e2001
+    @staticmethod
0e2001
+    def set_argparser(parser):
0e2001
+        parser.add_argument('module', nargs='*', metavar=_('MODULE'),
0e2001
+                            help=_('modules to download'))
0e2001
+        parser.add_argument("--enable_source_repos", action='store_true',
0e2001
+                            help=_('enable repositories with source packages'))
0e2001
+        parser.add_argument("--enable_debug_repos", action='store_true',
0e2001
+                            help=_('enable repositories with debug-info and debug-source packages'))
0e2001
+        parser.add_argument('--resolve', action='store_true',
0e2001
+                            help=_('resolve and download needed dependencies'))
0e2001
+        parser.add_argument('-n', '--newest-only', default=False, action='store_true',
0e2001
+                            help=_('download only packages from newest modules'))
0e2001
+
0e2001
+    def configure(self):
0e2001
+        # setup sack and populate it with enabled repos
0e2001
+        demands = self.cli.demands
0e2001
+        demands.sack_activation = True
0e2001
+        demands.available_repos = True
0e2001
+
0e2001
+        demands.load_system_repo = False
0e2001
+
0e2001
+        if self.opts.enable_source_repos:
0e2001
+            self.base.repos.enable_source_repos()
0e2001
+
0e2001
+        if self.opts.enable_debug_repos:
0e2001
+            self.base.repos.enable_debug_repos()
0e2001
+
0e2001
+        if self.opts.destdir:
0e2001
+            self.base.conf.destdir = self.opts.destdir
0e2001
+        else:
0e2001
+            self.base.conf.destdir = dnf.i18n.ucd(os.getcwd())
0e2001
+
0e2001
+    def run(self):
0e2001
+        """Execute the util action here."""
0e2001
+
0e2001
+        pkgs = self.base.sack.query().filterm(empty=True)
0e2001
+        no_matched_spec = []
0e2001
+        for module_spec in self.opts.module:
0e2001
+            try:
0e2001
+                pkgs = pkgs.union(self._get_packages_from_modules(module_spec))
0e2001
+            except dnf.exceptions.Error:
0e2001
+                no_matched_spec.append(module_spec)
0e2001
+        if no_matched_spec:
0e2001
+            msg = P_("Unable to find a match for argument: '{}'", "Unable to find a match for arguments: '{}'",
0e2001
+                     len(no_matched_spec)).format("' '".join(no_matched_spec))
0e2001
+            raise dnf.exceptions.Error(msg)
0e2001
+
0e2001
+        if self.opts.resolve:
0e2001
+            pkgs = pkgs.union(self._get_providers_of_requires(pkgs))
0e2001
+
0e2001
+        # download rpms
0e2001
+        self._do_downloads(pkgs)
0e2001
+
0e2001
+        # Create a repository at destdir with modular data
0e2001
+        remove_tmp_moduleyamls_files = []
0e2001
+        for repo in self.base.repos.iter_enabled():
0e2001
+            module_md_path = repo.get_metadata_path('modules')
0e2001
+            if module_md_path:
0e2001
+                filename = "".join([repo.id, "-", os.path.basename(module_md_path)])
0e2001
+                dest_path = os.path.join(self.base.conf.destdir, filename)
0e2001
+                shutil.copy(module_md_path, dest_path)
0e2001
+                remove_tmp_moduleyamls_files.append(dest_path)
0e2001
+        args = ["createrepo_c", "--update", "--unique-md-filenames", self.base.conf.destdir]
0e2001
+        p = subprocess.run(args)
0e2001
+        if p.returncode:
0e2001
+            msg = _("Creation of repository failed with return code {}. All downloaded content was kept on the system")
0e2001
+            msg = msg.format(p.returncode)
0e2001
+            raise dnf.exceptions.Error(msg)
0e2001
+        for file_path in remove_tmp_moduleyamls_files:
0e2001
+            os.remove(file_path)
0e2001
+
0e2001
+    def _do_downloads(self, pkgs):
0e2001
+        """
0e2001
+        Perform the download for a list of packages
0e2001
+        """
0e2001
+        pkg_dict = {}
0e2001
+        for pkg in pkgs:
0e2001
+            pkg_dict.setdefault(str(pkg), []).append(pkg)
0e2001
+
0e2001
+        to_download = []
0e2001
+
0e2001
+        for pkg_list in pkg_dict.values():
0e2001
+            pkg_list.sort(key=lambda x: (x.repo.priority, x.repo.cost))
0e2001
+            to_download.append(pkg_list[0])
0e2001
+        if to_download:
0e2001
+            self.base.download_packages(to_download, self.base.output.progress)
0e2001
+
0e2001
+    def _get_packages_from_modules(self, module_spec):
0e2001
+        """Gets packages from modules matching module spec
0e2001
+        1. From module artifacts
0e2001
+        2. From module profiles"""
0e2001
+        result_query = self.base.sack.query().filterm(empty=True)
0e2001
+        module_base = dnf.module.module_base.ModuleBase(self.base)
0e2001
+        module_list, nsvcap = module_base.get_modules(module_spec)
0e2001
+        if self.opts.newest_only:
0e2001
+            module_list = self.base._moduleContainer.getLatestModules(module_list, False)
0e2001
+        for module in module_list:
0e2001
+            for artifact in module.getArtifacts():
0e2001
+                query = self.base.sack.query(flags=hawkey.IGNORE_EXCLUDES).filterm(nevra_strict=artifact)
0e2001
+                if query:
0e2001
+                    result_query = result_query.union(query)
0e2001
+                else:
0e2001
+                    msg = _("No match for artifact '{0}' from module '{1}'").format(
0e2001
+                        artifact, module.getFullIdentifier())
0e2001
+                    logger.warning(msg)
0e2001
+            if nsvcap.profile:
0e2001
+                profiles_set = module.getProfiles(nsvcap.profile)
0e2001
+            else:
0e2001
+                profiles_set = module.getProfiles()
0e2001
+            if profiles_set:
0e2001
+                for profile in profiles_set:
0e2001
+                    for pkg_name in profile.getContent():
0e2001
+                        query = self.base.sack.query(flags=hawkey.IGNORE_EXCLUDES).filterm(name=pkg_name)
0e2001
+                        # Prefer to add modular providers selected by argument
0e2001
+                        if result_query.intersection(query):
0e2001
+                            continue
0e2001
+                        # Add all packages with the same name as profile described
0e2001
+                        elif query:
0e2001
+                            result_query = result_query.union(query)
0e2001
+                        else:
0e2001
+                            msg = _("No match for package name '{0}' in profile {1} from module {2}")\
0e2001
+                                .format(pkg_name, profile.getName(), module.getFullIdentifier())
0e2001
+                            logger.warning(msg)
0e2001
+        if not module_list:
0e2001
+            msg = _("No mach for argument '{}'").format(module_spec)
0e2001
+            raise dnf.exceptions.Error(msg)
0e2001
+
0e2001
+        return result_query
0e2001
+
0e2001
+    def _get_providers_of_requires(self, to_test, done=None, req_dict=None):
0e2001
+        done = done if done else to_test
0e2001
+        # req_dict = {}  {req : set(pkgs)}
0e2001
+        if req_dict is None:
0e2001
+            req_dict = {}
0e2001
+        test_requires = []
0e2001
+        for pkg in to_test:
0e2001
+            for require in pkg.requires:
0e2001
+                if require not in req_dict:
0e2001
+                    test_requires.append(require)
0e2001
+                req_dict.setdefault(require, set()).add(pkg)
0e2001
+
0e2001
+        if self.opts.newest_only:
0e2001
+            #  Prepare cache with all packages related affected by modular filtering
0e2001
+            names = set()
0e2001
+            for module in self.base._moduleContainer.getModulePackages():
0e2001
+                for artifact in module.getArtifacts():
0e2001
+                    name, __, __ = artifact.rsplit("-", 2)
0e2001
+                    names.add(name)
0e2001
+            modular_related = self.base.sack.query(flags=hawkey.IGNORE_EXCLUDES).filterm(provides=names)
0e2001
+
0e2001
+        requires = self.base.sack.query().filterm(empty=True)
0e2001
+        for require in test_requires:
0e2001
+            q = self.base.sack.query(flags=hawkey.IGNORE_EXCLUDES).filterm(provides=require)
0e2001
+
0e2001
+            if not q:
0e2001
+                #  TODO(jmracek) Shell we end with an error or with RC 1?
0e2001
+                logger.warning((_("Unable to satisfy require {}").format(require)))
0e2001
+            else:
0e2001
+                if self.opts.newest_only:
0e2001
+                    if not modular_related.intersection(q):
0e2001
+                        q.filterm(latest_per_arch_by_priority=1)
0e2001
+                requires = requires.union(q.difference(done))
0e2001
+        done = done.union(requires)
0e2001
+        if requires:
0e2001
+            done = self._get_providers_of_requires(requires, done=done, req_dict=req_dict)
0e2001
+
0e2001
+        return done
0e2001
--
0e2001
libgit2 1.1.0
0e2001