Base—The centerpiece of DNF

class dnf.Base

Instances of dnf.Base are the central point of functionality supplied by DNF. An application will typically create a single instance of this class which it will keep for the runtime needed to accomplish its packaging tasks. Plugins are managed by DNF and get a reference to dnf.Base object when they run.

Base instances are stateful objects holding references to various data sources and data sinks. To properly finalize and close off any handles the object may hold, client code should either call Base.close() when it has finished operations with the instance, or use the instance as a context manager. After the object has left the context, or its Base.close() has been called explicitly, it must not be used. Base.close() will delete all downloaded packages upon successful transaction.

comps

Is None by default. Explicit load via read_comps() initializes this attribute to a dnf.comps.Comps instance.

conf

An instance of dnf.conf.Conf, concentrates all the different configuration options. __init__() initializes this to usable defaults.

goal

An instance of dnf.goal.Goal that this Base object is using.

repos

A dnf.repodict.RepoDict instance, this member object contains all the repositories available.

sack

The Sack that this Base object is using. It needs to be explicitly initialized by fill_sack().

transaction

A resolved transaction object, a dnf.transaction.Transaction instance, or None if no transaction has been prepared yet.

__init__()

Init an instance with a reasonable default configuration. The constructor takes no arguments.

add_remote_rpms(path_list, strict=True, progress=None)

This function must be called before anything is added to the goal. Adds RPM files in path_list to the sack and return the list of respective dnf.package.Package instances. Downloads the RPMs to a temporary file for each path if it is a remote URL. Raises IOError if there are IO problems with files and strict=True. Raises dnf.exceptions.Error if the goal is not empty. progress, if given, should be a DownloadProgress instance which can be used to monitor the progress of the download.

add_security_filters(cmp_type, types=(), advisory=(), bugzilla=(), cves=(), severity=())

It modifies results of install, upgrade, and distrosync methods according to provided filters. cmp_type - only ‘eq’ or ‘gte’ allowed types - List or tuple with strings. Eg. bugfix, enhancement, newpackage, security advisory - List or tuple with strings. Eg. FEDORA-2201-123 bugzilla - List or tuple with strings. Include packages that fix a Bugzilla ID, Eg. 123123. cves - List or tuple with strings. Include packages that fix a CVE (Common Vulnerabilities and Exposures) ID. Eg. CVE-2201-0123 severity - List or tuple with strings. Includes packages that provide a fix for an issue of the specified severity.

reset_security_filters()

Reset all security filters

close()

Close all external handles the object holds. This is called automatically via context manager mechanism if the instance is handled using the with statement.

init_plugins([disabled_glob=None, cli=None])

Initialize plugins. If you want to disable some plugins pass the list of their name patterns to disabled_glob. When run from interactive script then also pass your dnf.cli.Cli instance.

pre_configure_plugins()

Configure plugins by running their pre_configure() method. It makes possible to change variables before repo files and rpmDB are loaded. It also makes possible to create internal repositories that will be affected by --disablerepo and --enablerepo.

configure_plugins()

Configure plugins by running their configure() method.

unload_plugins()

Unload all plugins.

fill_sack([load_system_repo=True, load_available_repos=True])

Setup the package sack. If load_system_repo is True, load information about packages in the local RPMDB into the sack. Else no package is considered installed during dependency solving. If load_available_repos is True, load information about packages from the available repositories into the sack.

This operation will call load() for repos as necessary and can take a long time. Adding repositories or changing repositories’ configuration does not affect the information within the sack until fill_sack() has been called.

Before this method is invoked, the client application should setup any explicit configuration relevant to the operation. This will often be at least conf.cachedir and the substitutions used in repository URLs. See Conf.substitutions.

Throws IOError exception in case cached metadata could not be opened.

Example:

#!/usr/bin/python3
import dnf

base = dnf.Base()
conf = base.conf
conf.cachedir = '/tmp/my_cache_dir'
conf.substitutions['releasever'] = '30'
conf.substitutions['basearch'] = 'x86_64'

base.repos.add_new_repo('my-repo', conf,
    baseurl=["http://download.fedoraproject.org/pub/fedora/linux/releases/$releasever/Everything/$basearch/os/"])
base.fill_sack()

print("Enabled repositories:")
for repo in base.repos.iter_enabled():
    print("id: {}".format(repo.id))
    print("baseurl: {}".format(repo.baseurl))
fill_sack_from_repos_in_cache(load_system_repo=True)

Prepare Sack and Goal objects and load all enabled repositories from cache only, it doesn’t download anything and it doesn’t check if metadata are expired. To successfully load a repository cache it requires repomd.xml plus metadata (xml, yaml) or repomd.xml plus generated cache files (solv, solvx). If there is not enough metadata given repo is either skipped or it throws a dnf.exceptions.RepoError exception depending on dnf.conf.Conf.skip_if_unavailable configuration.

All additional metadata are loaded if present but are not generally required. Note that some metadata like updateinfo.xml get processed into a solvx cache file and its sufficient to have either xml or solvx. Module metadata represented by modules.yaml are not processed therefore they are needed when they are defined in repomd.xml.

Example of loading all configured repositories from cache and printing available packages’ names:

#!/usr/bin/python3
import dnf

with dnf.Base() as base:
    base.read_all_repos()

    base.fill_sack_from_repos_in_cache(load_system_repo=False)

    query = base.sack.query().available()
    for pkg in query.run():
        print(pkg.name)

Example of loading a single repository and printing available packages’ names without reading repository configuration:

#!/usr/bin/python3
import dnf

with dnf.Base() as base:
    repo = dnf.repo.Repo("rawhide", base.conf)

    # Repository cache is also identified by its source therefore to find it you need to
    # set metalink, mirrorlist or baseurl to the same value from which it was created.
    repo.metalink = "https://mirrors.fedoraproject.org/metalink?repo=rawhide&arch=x86_64"

    base.repos.add(repo)

    base.fill_sack_from_repos_in_cache(load_system_repo=False)

    query = base.sack.query().available()
    for pkg in query.run():
        print(pkg.name)
do_transaction([display])

Perform the resolved transaction. Use the optional display object(s) to report the progress. display can be either an instance of a subclass of dnf.callback.TransactionProgress or a sequence of such instances. Raise dnf.exceptions.Error or dnf.exceptions.TransactionCheckError.

download_packages(pkglist, progress=None, callback_total=None)

Download packages in pkglist from remote repositories. Packages from local repositories or from the command line are not downloaded. progress, if given, should be a DownloadProgress and can be used by the caller to monitor the progress of the download. callback_total is a function accepting two parameters: total size of the downloaded content in bytes and time when the download process started, in seconds since the epoch. Raises DownloadError if some packages failed to download.

group_install(group_id, pkg_types, exclude=None, strict=True)

Mark group with corresponding group_id installed and mark the packages in the group for installation. Return the number of packages that the operation has marked for installation. pkg_types is a sequence of strings determining the kinds of packages to be installed, where the respective groups can be selected by including "mandatory", "default" or "optional" in it. If exclude is given, it has to be an iterable of package name glob patterns: group_install() will then not mark the respective packages for installation whenever possible. Parameter strict is a boolean indicating whether group packages that exist but are non-installable due to e.g. dependency issues should be skipped (False) or cause transaction to fail to resolve (True). Raises dnf.exceptions.CompsError in case the group doesn’t exist.

group_remove(group_id)

Mark group with corresponding group_id not installed. All the packages marked as belonging to this group will be marked for removal. Return the number of packages marked for removal in this call.

group_upgrade(group_id)

Upgrade group with corresponding group_id. If there has been packages added to the group’s comps information since installing on the system, they will be marked for installation. Similarly, removed packages get marked for removal. The remaining packages in the group are marked for an upgrade. The operation respects the package types from the original installation of the group.

environment_install(env_id, types, exclude=None, strict=True, exclude_groups=None)

Similar to group_install() but operates on environmental groups. exclude_groups is an iterable of group IDs that will not be marked as installed. Raises dnf.exceptions.CompsError in case the group doesn’t exist.

environment_remove(env_id)

Similar to group_remove() but operates on environmental groups.

environment_upgrade(env_id)

Similar to group_upgrade() but operates on environmental groups.

read_all_repos()

Read repository configuration from the main configuration file specified by dnf.conf.Conf.config_file_path and any .repo files under dnf.conf.Conf.reposdir. All the repositories found this way are added to repos.

read_comps(arch_filter=False)

Read comps data from all the enabled repositories and initialize the comps object. If arch_filter is set to True, the result is limited to system basearch.

reset(\*\*kwargs)

Reset the state of different Base attributes. Selecting attributes to reset is controlled by passing the method keyword arguments set to True. When called with no arguments the method has no effect.

argument passed

effect

goal=True

drop all the current packaging requests

repos=True

drop the current repositories (see repos). This won’t affect the package data already loaded into the sack.

sack=True

drop the current sack (see sack)

resolve(allow_erasing=False)

Resolve the marked requirements and store the resulting dnf.transaction.Transaction into transaction. Raise dnf.exceptions.DepsolveError on a depsolving error. Return True if the resolved transaction is non-empty.

Enabling allow_erasing lets the solver remove other packages while looking to fulfill the current packaging requests. For instance, this is used to allow the solver to remove dependants of a package being removed.

The exact operation of the solver further depends on the dnf.conf.Conf.best setting.

update_cache(timer=False)

Downloads and caches in binary format metadata for all known repos. Tries to avoid downloading whenever possible (e.g. when the local metadata hasn’t expired yet or when the metadata timestamp hasn’t changed).

If ‘timer’ equals ‘True’, DNF becomes more resource-aware, meaning DNF will not do anything if running on battery power and will terminate immediately if it’s too soon after the last successful update_cache operation.

When the method is used after fill_sack(), information about packages will not be updated.

package_signature_check(pkg)

Verify the GPG signature of the given package object. Returns tuple (result, error_string) where result is:

result

meaning

0

GPG signature verifies ok or verification is not required.

1

GPG verification failed but installation of the right GPG key might help.

2

Fatal GPG verification error, give up.

package_import_key(pkg, askcb=None, fullaskcb=None)

Retrieve a key for a package. If needed, use the given callback to prompt whether the key should be imported. Raises dnf.exceptions.Error if there are errors retrieving the keys.

askcb: callback function to use to ask permission to import a key. The arguments askcb should take are the package object, the userid of the key, and the keyid

fullaskcb: callback function to use to ask permission to import a key. This differs from askcb in that it gets passed a dictionary so that we can expand the values passed.

Callback functions return True if the key should be imported, False otherwise.

The Base class provides a number of methods to make packaging requests that can later be resolved and turned into a transaction. The pkg_spec argument some of them take must be a package specification recognized by dnf.subject.Subject. If these methods fail to find suitable packages for the operation they raise a MarkingError. Note that successful completion of these methods does not necessarily imply that the desired transaction can be carried out (e.g. for dependency reasons).

downgrade(pkg_spec)

Mark packages matching pkg_spec for downgrade.

install(pkg_spec, reponame=None, strict=True, forms=None)

Mark packages matching pkg_spec for installation. reponame can be a name of a repository or a list of repository names. If given, the selection of available packages is limited to packages from these repositories. If strict is set to False, the installation ignores packages with dependency solving problems. Parameter forms has the same meaning as in dnf.subject.Subject.get_best_query().

package_downgrade(pkg, strict=False)

If pkg is a dnf.package.Package in an available repository, mark the matching installed package for downgrade to pkg. If strict=False it ignores problems with dep-solving.

package_install(pkg, strict=True)

Mark pkg (a dnf.package.Package instance) for installation. Ignores package that is already installed. strict has the same meaning as in install().

package_upgrade(pkg)

If pkg is a dnf.package.Package in an available repository, mark the matching installed package for upgrade to pkg.

autoremove()

Removes all ‘leaf’ packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package.

remove(pkg_spec, reponame=None, forms=None)

Mark packages matching pkg_spec for removal. reponame and forms have the same meaning as in install().

upgrade(pkg_spec, reponame=None)

Mark packages matching pkg_spec for upgrade. reponame has the same meaning as in install().

upgrade_all(reponame=None)

Mark all installed packages for an upgrade. reponame has the same meaning as in install().

urlopen(url, repo=None, mode='w+b', \*\*kwargs):

Open the specified absolute url and return a file object which respects proxy setting even for non-repo downloads

install_specs(install, exclude=None, reponame=None, strict=True, forms=None)

Provides unified way to mark packages, groups or modules for installation. The install and exclude arguments have to be iterables containing specifications of packages (e.g. ‘dnf’) or groups/modules (e.g. ‘@core’). Specifications from the exclude list will not be marked for installation. The reponame, strict and forms parameters have the same meaning as in install(). In case of errors the method raises dnf.exceptions.MarkingErrors.

Example to install two groups and a package:

#!/usr/bin/python3
import dnf
import dnf.cli.progress

base = dnf.Base()
base.read_all_repos()
base.fill_sack()

base.install_specs(['acpi', '@Web Server', '@core'])
print("Resolving transaction...",)
base.resolve()
print("Downloading packages...")
progress = dnf.cli.progress.MultiFileProgressMeter()
base.download_packages(base.transaction.install_set, progress)
print("Installing...")
base.do_transaction()