Debian Codegraph @

kiwi/repository/dnf5.py

raw
1 # Copyright (c) 2023 Marcus Schäfer. All rights reserved.
2 #
3 # This file is part of kiwi.
4 #
5 # kiwi is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # kiwi is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with kiwi. If not, see <http://www.gnu.org/licenses/>
17 #
18 import os
19 import glob
20 from configparser import ConfigParser
21 from typing import List, Dict
22
23 # project
24 import kiwi.defaults as defaults
25 from kiwi.utils.temporary import (
26 Temporary, TmpT
27 )
28 from kiwi.defaults import Defaults
29 from kiwi.command import Command
30 from kiwi.repository.base import RepositoryBase
31 from kiwi.path import Path
32 from kiwi.utils.rpm_database import RpmDataBase
33 from kiwi.utils.toenv import ToEnv
34
35
36 class RepositoryDnf5(RepositoryBase):
37 """
38 **Implements repository handling for next generation dnf5 package manager**
39
40 :param str shared_dnf_dir: shared directory between image root
41 and build system root
42 :param str runtime_dnf_config_file: dnf runtime config file name
43 :param dict command_env: customized os.environ for dnf
44 :param str runtime_dnf_config: instance of :class:`ConfigParser`
45 """
46
47 def post_init(self, custom_args: List = []) -> None:
48 """
49 Post initialization method
50
51 Store custom dnf arguments and create runtime configuration
52 and environment
53
54 :param list custom_args: dnf arguments
55 """
56 self.runtime_dnf_config_file = TmpT(name='')
57 self.custom_args = custom_args
58 self.exclude_docs = False
59 self.locale = None
60 self.target_arch = None
61
62 # extract custom arguments not used in dnf call
63 if 'exclude_docs' in self.custom_args:
64 self.custom_args.remove('exclude_docs')
65 self.exclude_docs = True
66
67 if 'check_signatures' in self.custom_args:
68 self.custom_args.remove('check_signatures')
69 self.gpg_check = '1'
70 else:
71 self.gpg_check = '0'
72
73 for argument in self.custom_args:
74 if '_install_langs' in argument:
75 self.locale = argument
76 elif '_target_arch' in argument:
77 self.target_arch = argument
78 if self.locale:
79 self.custom_args.remove(self.locale)
80 if self.target_arch:
81 self.custom_args.remove(self.target_arch)
82 self.target_arch = self.target_arch.split('%')[1]
83
84 self.repo_names: List = []
85
86 # dnf support is based on creating repo files which contains
87 # path names to the repo and its cache. In order to allow a
88 # persistent use of the files in and outside of a chroot call
89 # an active bind mount from RootBind::mount_shared_directory
90 # is expected and required
91 manager_base = self.shared_location + '/dnf'
92
93 self.shared_dnf_dir = {
94 'reposd-dir': manager_base + '/repos',
95 'cache-dir': manager_base + '/cache',
96 'pluginconf-dir': manager_base + '/pluginconf',
97 'vars-dir': manager_base + '/vars'
98 }
99
100 self.runtime_dnf_config_file = Temporary(
101 path=self.root_dir, prefix='kiwi_dnf5.config'
102 ).unmanaged_file()
103
104 self.dnf_args = [
105 '--config', self.runtime_dnf_config_file.name, '-y', '--disable-plugin=priorities,versionlock'
106 ] + self.custom_args
107
108 self.command_env = self._create_dnf_runtime_environment()
109
110 # config file parameters for dnf tool
111 self._create_runtime_config_parser()
112 self._write_runtime_config()
113
114 def setup_package_database_configuration(self) -> None:
115 """
116 Setup rpm macros for bootstrapping and image building
117
118 1. Create the rpm image macro which persists during the build
119 2. Create the rpm bootstrap macro to make sure for bootstrapping
120 the rpm database location matches the host rpm database setup.
121 This macro only persists during the bootstrap phase. If the
122 image was already bootstrapped a compat link is created instead.
123 """
124 rpmdb = RpmDataBase(
125 self.root_dir, Defaults.get_custom_rpm_image_macro_name()
126 )
127 if self.locale:
128 rpmdb.set_macro_from_string(self.locale)
129 rpmdb.write_config()
130
131 rpmdb = RpmDataBase(self.root_dir)
132 if rpmdb.has_rpm():
133 rpmdb.link_database_to_host_path()
134 else:
135 rpmdb.set_database_to_host_path()
136 # SUSE compat code:
137 #
138 # Manually adding the compat link /var/lib/rpm that points to the
139 # rpmdb location as it is configured in the host rpm setup. DNF makes
140 # use of the host setup to bootstrap or to read the signing keys
141 # from the rpm database setup provisioned by rpm itself (macro level).
142 # It assumes the host setup is the default for the system being built.
143 #
144 # For SUSE this is causing a mismatch as the host setup is not the RPM
145 # default (/var/lib/rpm) and SUSE distros proactively relocate the rpm
146 # database from the default location to a custom one when the
147 # rpm package and related macros are installed for the first time.
148 rpmdb.init_database()
149 image_rpm_compat_link = '/var/lib/rpm'
150 host_rpm_dbpath = rpmdb.rpmdb_host.expand_query('%_dbpath')
151 if host_rpm_dbpath != image_rpm_compat_link:
152 Path.create(
153 self.root_dir + os.path.dirname(image_rpm_compat_link)
154 )
155 Command.run(
156 [
157 'ln', '-s', '--no-target-directory',
158 ''.join(['../..', host_rpm_dbpath]),
159 self.root_dir + image_rpm_compat_link
160 ], raise_on_error=False
161 )
162
163 def use_default_location(self) -> None:
164 """
165 Setup dnf repository operations to store all data
166 in the default places
167 """
168 self.shared_dnf_dir['reposd-dir'] = \
169 self.root_dir + '/etc/yum.repos.d'
170 self.shared_dnf_dir['cache-dir'] = \
171 self.root_dir + '/var/cache/libdnf5'
172 self.shared_dnf_dir['pluginconf-dir'] = \
173 self.root_dir + '/etc/dnf/libdnf5-plugins'
174 self.shared_dnf_dir['vars-dir'] = \
175 self.root_dir + '/etc/dnf/vars'
176 self._create_runtime_config_parser()
177 self._write_runtime_config()
178
179 def runtime_config(self) -> Dict:
180 """
181 dnf runtime configuration and environment
182
183 :return: dnf_args:list, command_env:dict
184
185 :rtype: dict
186 """
187 return {
188 'dnf_args': self.dnf_args,
189 'command_env': self.command_env
190 }
191
192 def add_repo(
193 self, name: str, uri: str, repo_type: str = 'rpm-md',
194 prio: int = None, dist: str = None, components: str = None,
195 user: str = None, secret: str = None, credentials_file: str = None,
196 repo_gpgcheck: bool = False, pkg_gpgcheck: bool = False,
197 sourcetype: str = None, customization_script: str = None,
198 architectures: str = None
199 ) -> None:
200 """
201 Add dnf repository
202
203 :param str name: repository base file name
204 :param str uri: repository URI
205 :param str repo_type: repostory type name
206 :param int prio: dnf repostory priority
207 :param str dist: unused
208 :param str components: unused
209 :param str user: unused
210 :param str secret: unused
211 :param str credentials_file: unused
212 :param bool repo_gpgcheck: enable repository signature validation
213 :param bool pkg_gpgcheck: enable package signature validation
214 :param str sourcetype:
215 source type, one of 'baseurl', 'metalink' or 'mirrorlist'
216 :param str customization_script:
217 custom script called after the repo file was created
218 :param str architectures: unused
219 """
220 repo_file = self.shared_dnf_dir['reposd-dir'] + '/' + name + '.repo'
221 self.repo_names.append(name + '.repo')
222 if os.path.exists(uri):
223 # dnf requires local paths to take the file: type
224 uri = 'file://' + uri
225 repo_config = ConfigParser(interpolation=None)
226 repo_config.add_section(name)
227 repo_config.set(
228 name, 'name', name
229 )
230 repo_config.set(
231 name, sourcetype if sourcetype else 'baseurl', uri
232 )
233 if prio:
234 repo_config.set(
235 name, 'priority', format(prio)
236 )
237 repo_config.set(
238 name, 'repo_gpgcheck', '1' if repo_gpgcheck else '0'
239 )
240 repo_config.set(
241 name, 'gpgcheck', '1' if pkg_gpgcheck else '0'
242 )
243 if Defaults.is_buildservice_worker():
244 # when building in the build service, modular metadata is
245 # inaccessible. In order to use modular content in the build
246 # service, we need to disable modular filtering, which is
247 # done with module_hotfixes option
248 repo_config.set(
249 name, 'module_hotfixes', '1'
250 )
251 if not os.path.isdir(self.shared_dnf_dir['reposd-dir']):
252 Path.create(self.shared_dnf_dir['reposd-dir'])
253 with open(repo_file, 'w') as repo:
254 repo_config.write(repo)
255 if customization_script:
256 self.run_repo_customize(customization_script, repo_file)
257
258 def import_trusted_keys(self, signing_keys: List) -> None:
259 """
260 Imports trusted keys into the image
261
262 :param list signing_keys: list of the key files to import
263 """
264 rpmdb = RpmDataBase(self.root_dir)
265 for key in signing_keys:
266 rpmdb.import_signing_key_to_image(key)
267
268 def delete_repo(self, name: str) -> None:
269 """
270 Delete dnf repository
271
272 :param str name: repository base file name
273 """
274 Path.wipe(
275 self.shared_dnf_dir['reposd-dir'] + '/' + name + '.repo'
276 )
277
278 def delete_all_repos(self) -> None:
279 """
280 Delete all dnf repositories
281 """
282 Path.wipe(self.shared_dnf_dir['reposd-dir'])
283 Path.create(self.shared_dnf_dir['reposd-dir'])
284
285 def delete_repo_cache(self, name: str) -> None:
286 """
287 Delete dnf repository cache
288
289 The cache data for each repository is stored in a directory
290 and additional files all starting with the repository name.
291 The method glob deletes all files and directories matching
292 the repository name followed by any characters to cleanup
293 the cache information
294
295 :param str name: repository name
296 """
297 dnf_cache_glob_pattern = ''.join(
298 [self.shared_dnf_dir['cache-dir'], os.sep, name, '*']
299 )
300 for dnf_cache_file in glob.iglob(dnf_cache_glob_pattern):
301 Path.wipe(dnf_cache_file)
302
303 def cleanup_unused_repos(self) -> None:
304 """
305 Delete unused dnf repositories
306
307 Repository configurations which are not used for this build
308 must be removed otherwise they are taken into account for
309 the package installations
310 """
311 repos_dir = self.shared_dnf_dir['reposd-dir']
312 repo_files = list(os.walk(repos_dir))[0][2]
313 for repo_file in repo_files:
314 if repo_file not in self.repo_names:
315 Path.wipe(repos_dir + '/' + repo_file)
316
317 def _create_dnf_runtime_environment(self) -> Dict:
318 for dnf_dir in list(self.shared_dnf_dir.values()):
319 Path.create(dnf_dir)
320 ToEnv(self.root_dir, defaults.PACKAGE_MANAGER_ENV_VARS)
321 return dict(
322 os.environ, LANG='C'
323 )
324
325 def _create_runtime_config_parser(self) -> None:
326 self.runtime_dnf_config = ConfigParser(interpolation=None)
327 self.runtime_dnf_config["main"] = {
328 "system_cachedir": self.shared_dnf_dir['cache-dir'],
329 "reposdir": self.shared_dnf_dir['reposd-dir'],
330 "varsdir": self.shared_dnf_dir['vars-dir'],
331 "pluginconfpath": self.shared_dnf_dir['pluginconf-dir'],
332 "keepcache": "1",
333 "debuglevel": "2",
334 "best": "1",
335 "obsoletes": "1",
336 "plugins": "0",
337 "gpgcheck": self.gpg_check,
338 }
339 if self.exclude_docs:
340 self.runtime_dnf_config["main"]["tsflags"] = "nodocs"
341 if self.target_arch:
342 self.runtime_dnf_config["main"].update({
343 "arch": self.target_arch,
344 "ignorearch": "1",
345 })
346
347 def _write_runtime_config(self) -> None:
348 with open(self.runtime_dnf_config_file.name, 'w') as config:
349 self.runtime_dnf_config.write(config)
350
351 def cleanup(self) -> None:
352 """
353 Delete intermediate dnf config file
354 """
355 if os.path.isfile(self.runtime_dnf_config_file.name):
356 os.unlink(self.runtime_dnf_config_file.name)