Guía de los paquetes binarios

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Binary package guide and the translation is 23% complete.
Outdated translations are marked like this.

Aparte del soporte usual para ebuilds, Portage ofrece soporte para construir e instalar paquetes binarios. Esta guía explica cómo crearlos, cómo instalarlos y cómo poner en marcha un servidor de paquetes binarios.

This guide will focus on binary package use, creation, distribution, and maintenance, and a few more advanced topics on dealing with binary packages will be covered near the end.

See also
See the binary package quickstart article for information on using pre-built binary packages from the Gentoo binary package host.
Nota
Todas las herramientas utilizadas en esta guía forma parte de sys-apps/portage a menos que se diga lo contrario.

Why use binary packages on Gentoo?

Hay muchas razones por la que a los administradores de sistemas Gentoo les gusta utilizar instalaciones de paquetes binarios.

  1. En primer lugar, permite a los administradores mantener actualizados los sistemas que tienen características similares. Compilar todo desde el código fuente puede llevar mucho tiempo. El mantenimiento de varios sistemas similares, probablemente algunos de ellos con hardware antiguo, puede ser mucho más fácil si solo un sistema tiene que compilar todo desde el código fuente y el resto de sistemas reutilizan los paquetes binarios.
  2. Una segunda razón es hacer actuaarchivo de medio ambientelizaciones seguras. Es importante mantener utilizables los sistemas de misión crítica la mayor parte del tiempo posible. Esto se puede hacer con un servidor de ensayo que realiza todas las actualizaciones en sí mismo en primer lugar. Una vez el servidor de ensayo se encuentra en un buen estado, las actualizaciones se pueden aplicar a los sistemas críticos. Una variante de este enfoque es hacer los cambios en un entorno chroot en el mismo sistema y utilizar los binarios creados allí en el sistema real.
  3. Una tercera razón es a modo de copia de seguridad. A menudo, los paquetes binarios son la única forma de recuperar un sistema que no funciona (por ejemplo, el compilador no funciona). Tener los binarios preconstruidos a mano ya sea en un servidor de paquetes binarios o localmente puede ser de gran ayuda en caso de que se rompa la cadena de herramientas.
  4. Por último, también permite la actualización de sistemas muy antiguos . La tarea de actualizar sistemas muy antiguos se puede aliviar en gran medida si se utilizan paquetes binarios. Por lo general es útil para instalar paquetes binarios en los sistemas antiguos, ya que no requieren de dependencias en tiempo de compilación para instalarse o actualizarse. Los paquetes binarios también evitan fallos de los procesos de construcción, ya que están preconstruidos.

Binary package formats

Two binary package formats for use in Gentoo exist, XPAK and GPKG. Starting with v3.0.31, Portage supports the new binary package format GPKG. The GPKG format solves issues with the legacy XPAK format and offers the benefit of new features, however it is not backward compatible with the legacy XPAK format.

System administrators using older versions of Portage (<=v3.0.30) should continue to use the legacy XPAK format, which is Portage's default setting.

Motivation for the newer GPKG format design can be found in GLEP 78: Gentoo binary package container format. Bugs bug #672672 and bug #820578 also provide helpful details.

To instruct Portage to use the GPKG format, change the BINPKG_FORMAT value in /etc/portage/make.conf.

ARCHIVO /etc/portage/make.confSpecify GPKG binary package format
BINPKG_FORMAT="gpkg"

This guide mostly applies to both formats; where this is not the case it will be noted. See the Understanding the binary package format section for technical details on the binary package formats themselves.

Utilizar paquetes binarios

General prerequisites

Para que los paquetes binarios se puedan utilizar en otros sistemas, deben cumplir algunos requisitos.

  • La arquitectura del cliente y del servidor y su CHOST deben coincidir.
  • Las variables CFLAGS y CXXFLAGS que se utilyzaron para construir los paquetes binarios deben ser compatibles con todos los clientes.
  • Los ajustes USE de características específicas del juego de instrucciones del procesador (como MMX, SSE, etc.) deben seleccionarse con cuidado ya que todos los clientes deben ofrecer soporte para ellos.
Nota
Binary packages that are distributed as part of Gentoo's official Binhost project use a minimum instruction set and conservative compiler settings in order to be as widely usable as possible. By way of example, amd64 keyworded packages are built with -march=x86-64 -mtune=generic, which works for any machine which runs the x86-64 (amd64) instruction set.
Importante
Portage no puede validar si se cumplen estos requisitos, esto es responsabilidad del administrador del sistema.

Handling *FLAGS in detail

The app-misc/resolve-march-native utility can be used to find a subset of CFLAGS that is supported by both the server and client(s). For example, the host might return:

user $resolve-march-native
 -march=skylake -mabm -mrtm --param=l1-cache-line-size=64 --param=l1-cache-size=32 --param=l2-cache-size=12288 

While the client might return:

user $resolve-march-native
 -march=ivybridge -mno-rdrnd --param=l1-cache-line-size=64 --param=l1-cache-size=32 --param=l2-cache-size=3072 

In this example CFLAGS could be set to -march=ivybridge -mno-rdrnd since -march=ivybridge is a full subset of -march=skylake. -mabm and -mrtm are not included as these are not supported by the client. However, -mno-rdrnd is included as the client does not support -mrdrnd. To find which -march's are subsets of others, check the gcc manual, if there is no suitable subset set e.g. -march=x86-64.

Optionally, it is also possible to set -mtune=some-arch or -mtune=native to tell gcc to tune code to a specific arch. In contrast to -march, the -mtune argument does not prevent code from being executed on other processors. For example, to compile code which is compatible with ivybridge and up but is tuned to run best on skylake set CFLAGS to -march=ivybridge -mtune=skylake. When -mtune is not set it defaults to whatever -march is set to.

When changing -march to a lower subset for using binary packages on a client, a full recompilation is required to make sure that all binaries are compatible with the client's processor, to save time packages that are not compiled with e.g. gcc/clang can be excluded:

user $emerge -e @world --exclude="acct-group/* acct-user/* virtual/* app-eselect/* sys-kernel/* sys-firmware/* dev-python/* dev-java/* dev-ruby/* dev-perl/* dev-lua/* dev-php/* dev-tex/* dev-texlive/* x11-themes/* */*-bin"

Similarly, app-portage/cpuid2cpuflags can be used to find a suitable subset of processor specific instruction set USE flags. For example, the host might return:

user $cpuid2cpuflags
 CPU_FLAGS_X86: aes avx avx2 f16c fma3 mmx mmxext pclmul popcnt rdrand sse sse2 sse3 sse4_1 sse4_2 ssse3 

While the client might return:

user $cpuid2cpuflags
 CPU_FLAGS_X86: avx f16c mmx mmxext pclmul popcnt sse sse2 sse3 sse4_1 sse4_2 ssse3 

In this example CPU_FLAGS_X86 can be set to avx f16c mmx mmxext pclmul popcnt sse sse2 sse3 sse4_1 sse4_2 ssse3 in /etc/portage/make.conf because these flags are supported by both the client and the host

Aparte de esto, Portage comprobará si el paquete binario se construye utilizando los mismos ajustes USE que se esperan en el cliente. Si se construye un paquete con una combinación distinta de ajustes USE, Portage, bien ignorará el paquete binario (y utilizará un ebuild basado en fuentes), bien fallará, dependiendo de las opciones que se pasen a la orden emerge cuando se invoque (leer Instalar paquetes binarios).

En los cliente se requieren algunos cambios en la configuración para poder utilizar paquetes binarios.

Instalar paquetes binarios

Se necesitan algunas opciones para pasar a la orden emerge que informará a Portage sobre el uso de paquetes binarios:

Option Descripción
--usepkg (-k) Intenta utilizar el o los paquetes binarios en el directorio local packages. Es útil cuando se utilizan servidores de paquetes binarios que permitan montar NFS o SSHFS. Si no se encuentran los paquetes binarios solicitados, se realizará una instalación regular (basada en fuentes) .
--usepkgonly (-K) Es similar a --usepkg (-k) pero fallará si no se encuentra el paquete binario solicitado. Esta opción es útil únicamente si se van a utilizar paquetes binarios preconstruidos.
--getbinpkg (-g) Descarga el o los paquetes binarios desde un servidor remote. Si no se encuentran los paquetes binarios solicitados, se realizará una instalación regular (basada en fuentes).
--getbinpkgonly (-G) Es similar a --getbinpkg (-g) pero fallará si no se pueden descargar el o los paquetes binarios. Esta opción es útil solo si se van a utilizar paquetes binarios preconstruidos.

| --usepkg (-k) || Tries to use the binary package(s) in the locally available packages directory. Useful when using NFS or SSHFS mounted binary package hosts. If the binary packages are not found, a regular (source-based) installation will be performed. |-

| --usepkgonly (-K) || Similar to --usepkg (-k) but fail if the binary package cannot be found. This option is useful if only pre-built binary packages are to be used. |-

| --getbinpkg (-g) || Download the binary package(s) from a remote binary package host. If the binary packages are not found, a regular (source-based) installation will be performed. |-

| --getbinpkgonly (-G) || Similar to --getbinpkg (-g) but will fail if the binary package(s) cannot be downloaded. This option is useful if only pre-built binary packages are to be used. |-

|}

Para utilizar instalaciones basadas en paquetes binarios de forma automática, se puede añadir la opción elegida a la variable EMERGE_DEFAULT_OPTS:

ARCHIVO /etc/portage/make.confObtener los paquetes binarios de forma automática y abortar la instlación si no están disponibles
EMERGE_DEFAULT_OPTS="${EMERGE_DEFAULT_OPTS} --getbinpkgonly"

Hay una característica (FEATURE) de Portage que implementa automáticamente el equivalente a --getbinpkg (-g) sin tener que actualizar la variable EMERGE_DEFAULT_OPTS al valor getbinpkg.

ARCHIVO /etc/portage/make.confHabilitar getbinpkg en la variable FEATURES
FEATURES="getbinpkg"

Verify binary package OpenPGP signatures

Importante
OpenPGP signing and verification is only available for the GPKG binpkg format.

Portage will try to verify the binary package's signature whenever possible, but users must first set up trusted local keys. app-portage/getuto can be used to set up a local trust anchor and update the keys in /etc/portage/gnupg. Portage calls getuto automatically with --getbinpkg or --getbinpkgonly.

This configures portage such that it trusts the Gentoo Release Engineering keys as also contained in the package sec-keys/openpgp-keys-gentoo-release for binary installation purposes.

Changes to the configuration can be done as root using gpg with the parameter --homedir=/etc/portage/gnupg. This way allows importing additional signing keys (e.g. for non-standard installation sources) and declare them as trusted.

To add a custom signing key:

  1. Generate (or use an existing) key with signing abilities, and export the public key to a file.
  2. Run getuto if it has never run:
    root #getuto
  3. Use gpg --homedir=/etc/portage/gnupg --import public.key to import the public key in portage's keyring.
  4. Trust and sign this key using the key created by getuto. In order to do this, first get the password to unlock the key at /etc/portage/gnupg/pass, then use:
    root #gpg --homedir=/etc/portage/gnupg --edit-key YOURKEYID
    Type sign, yes, paste (or type) the password. The key is now signed. To trust it, type trust, then 4 to trust it fully. Finally, type save.
  5. Update the trustdb so that GPG considers the key valid:
    root #gpg --homedir=/etc/portage/gnupg --check-trustdb

If you hit any issues, check if a pre-existing /etc/portage/gnupg existed. If it did, move it away and then repeat the above steps.

Congratulations, Portage now has a working keyring!

Importante
Trusting the key marginally or less will not work

By default, Portage will only verify GPG signatures when a signature file is found in a package, which allows the user to mix signed and unsigned GPKG binary packages from different sources, and allows to use old XPAK format binary packages.

If the user wishes to force signature verification, the binpkg-request-signature feature needs to be enabled. This feature assumes that all packages should be signed and rejects any unsigned package. Note that this feature does not support per-binhost configuration.

ARCHIVO /etc/portage/make.confEnabling Portage's binpkg-request-signature feature
# Require that all binpkgs be signed and reject them if they are not (or have an invalid sig)
FEATURES="binpkg-request-signature"

Obtener paquetes desde un servidor de paquetes binarios

Cuando se utiliza una gran cantidad de servidores de paquetes binarios, los clientes necesitan tener definida la variable PORTAGE_BINHOST. De otro modo el cliente no sabrá dónde se almacenan los paquetes binarios lo que resultará en que Portage no podrá recuperarlos.

When using a binary package host, clients need to have the PORTAGE_BINHOST variable set in /etc/portage/make.conf or the sync-uri variable in /etc/portage/binrepos.conf. The latter option using /etc/portage/binrepos.conf is preferred. Without this configuration, the client will not know where the binary packages are stored which results in Portage being unable to retrieve them.

ARCHIVO /etc/portage/binrepos.confSetting binhost sync-uri
[binhost]
sync-uri = https://example.com/binhost
priority = 10

La variable PORTAGE_BINHOST utiliza una lista de URIs separada por espacios. Esto permite a los administradores utilizar varios servidores de paquetes binarios de forma simultánea. El URI siempre debe apuntar al directorio en el que el reside el fichero Packages.

Many Gentoo stages already come with a preinstalled /etc/portage/binrepos.conf file, which points to the corresponding binary packages generated during the stage builds.

Nota
El soporte para múltiples servidores de paquetes binarios está algo incompleto. Si varios servidores ofrecen un paquete binario para la misma versión del mismo, entonces se considerará solo el primero. Esto puede ser un problema cuando estos paquetes binarios difieren en su configuración de variable USE y la configuración de variable USE de un paquete binario más reciente coincidiera con la configuración de los sistemas.

Reinstalar paquetes binarios modificados

Si se pasa la opción --rebuilt-binaries a emerge se reinstalarán todos los paquetes que se han reconstruido desde que se instaló el paquete. Esto es útil en caso de que se utilicen herramientas de reconstrucción como revdep-rebuild o python-updater en el servidor paquete binario.

Una opción relacionada es --rebuilt-binaries-timestamp. Hace que emerge no considere los paquetes binarios para una reinstalar si esos paquetes binarios se han reconstruido antes de la marca de tiempo dada. Esto es útil para evitar la reinstalación de todos los paquetes, si el servidor de paquetes binarios se tuvo que reconstruir desde cero, de lo contrario utilice --rebuilt-binaries.

Ajustes adicionales en el cliente

Además de la característica getbinpkg, Portage también acepta la característica binpkg-logs. Ésta controla si los archivos de registro de las instalaciones exitosas de paquetes binarios se deben mantener. Solo es relevante si se ha definido la variable PORT_LOGDIR y está habilitada por defecto.

Similar a la exclusión de los paquetes binarios para un determinado conjunto de paquetes o categorías, los clientes se pueden configurar para excluir la instalación de paquetes binarios para un determinado conjunto de paquetes o categorías.

Para hacer esto, utilice la opción --usepkg-exclude:

root #emerge -uDNg @world --usepkg-exclude "sys-kernel/gentoo-sources virtual/*"

Para habilitar estos ajustes adicionales para cada orden emerge, añadir las opciones a la variable EMERGE_DEFAULT_OPTS dentro del fichero make.conf:

ARCHIVO /etc/portage/make.confHabilitar ajustes para emerge en cada invocación
EMERGE_DEFAULT_OPTS="${EMERGE_DEFAULT_OPTS} --usepkg-exclude 'sys-kernel/gentoo-sources virtual/*'"

Updating packages on the binary package host

Importante
Do not use --changed-use(-U) when updating packages on the binary package host, doing so will cause packages with added or removed USE flags to be skipped, which will cause their installation from binary package on the client to fail due to non-matching USE between the source ebuild and binary package (if the client's --binpkg-respect-use=y, the default). Use --newuse(-N), which will always rebuild packages even for added or removed USE flags, ensuring the binary package stays in sync with the source ebuild.

Crear paquetes binarios

Hay tres formas principales para la creación de paquetes binarios:

  1. Después de una instalación normal, utilizando la aplicación quickpkg
  2. Explícitamente durante una operación emerge utilizando la opción --buildpkg (-b)
  3. Automáticamente mediante el uso del valor buildpkg en la variable FEATURES de Portage

Los tres métodos crearán un paquete binario en el directorio al que apunta la variable PKGDIR (cuyo valor por defecto es /usr/portage/packages).

Utilizar quickpkg

La aplicación quickpkg toma como argumentos uno o más átomos de dependencia (o conjuntos de paquetes) y crea paquetes binarios para todos los paquetes instalados que concuerdan con ese átomo.

Una advertencia sobre el uso de este método: Se basa en los archivos instalados, lo cual puede ser un problema en el caso de archivos de configuración. Los administradores suelen cambiar los archivos de configuración después de instalar el software. Debido a que esto podrían filtrarse datos importantes (incluso confidenciales) en los paquetes. Por defecto, quickpkg no incluye archivos de configuración que están protegidos mediante el método CONFIG_PROTECT. Para forzar la inclusión de archivos de configuración, utilice las opciones --include-config o --include-unmodified-config.

Por ejemplo, para crear paquetes binarios de todas las versiones de GCC instaladas:

root #quickpkg sys-devel/gcc

To create binary packages for the system set:

root #quickpkg @system

Para crear paquetes binarios de todos los paquetes instalados en el sistema, utilice la expresión *:

root #quickpkg "*/*"

Utilizar --buildpkg como opción de emerge

Cuando se instala software mediante emerge, se puede solicitar a Portage que cree paquetes binarios utilizando la opción --buildpkg (-b):

root #emerge --ask --buildpkg sys-devel/gcc

También es posible pedirle a Portage que únicamente cree los paquetes binarios pero que no instale el software en el sistema vivo. Para hacer esto se puede utilizar la opción --buildpkgonly (-B):

root #emerge --ask --buildpkgonly sys-devel/gcc

El último enfoque requiere sin embargo que estén instaladas previamente todas las dependencias necesarias en el momento de la construcción.

Implementar buildpkg como una característica de Portage

La forma más común para crear automáticamente paquetes binarios cuando Portage instala un paquete es utilizar la característica buildpkg, que se puede configurar en /etc/portage/make.conf de esta forma:

ARCHIVO /etc/portage/make.confHabilitar la característica buildpkg de Portage's
FEATURES="buildpkg"

Cuando se activa esta característica, cada vez que Portage instala software se creará también un paquete binario.

Evitar la creación de algunos paquetes

Es posible indicarle a Portage que no cree paquetes binarios para un grupo de paquetes o categorías seleccionados. Esto se hace pasando la opción --buildpkg-exclude a emerge:

root #emerge -uDN @world --buildpkg --buildpkg-exclude "virtual/* sys-kernel/*-sources"

Esto se podría utilizar para paquetes en los que se obtiene poco o ningún beneficio teniendo instalado el paquete binario disponible. Ejemplos de ello serían los paquetes fuentes del núcleo Linux o paquetes binarios de los desarrolladores del propio paquete (los que terminan en -bin como www-client/firefox-bin).

Binary package compression formats

It is possible to use a specific compression type on binary packages. Currently, the following formats are supported: bzip2, gzip, lz4, lzip, lzop, xz, and zstd. Defaults to zstd. Review man make.conf and search for BINPKG_COMPRESS for the most up-to-date information.

The compression format can be specified via make.conf.

ARCHIVO /etc/portage/make.confSpecify binary package compression format
BINPKG_COMPRESS="lz4"

Note that the compression type used might require extra dependencies to be installed, for example, in this case app-arch/lz4.

Binary package OpenPGP signing

Importante
OpenPGP signing and verification is only available for the GPKG binpkg format.

A PGP signature enables Portage to check the creator and integrity of a binary package, and to perform trust management based on PGP keys. The binary package signing feature is disabled by default. To use it, enable the binpkg-signing feature. Note that whether this feature is enabled does not affect the signature verification feature.

ARCHIVO /etc/portage/make.confEnabling Portage's binpkg-signing feature
FEATURES="binpkg-signing"

Users also need to set the BINPKG_GPG_SIGNING_GPG_HOME and BINPKG_GPG_SIGNING_KEY variables for Portage to find the signing key.

ARCHIVO /etc/portage/make.confConfiguring Portage's signing key
BINPKG_GPG_SIGNING_GPG_HOME="/root/.gnupg"
BINPKG_GPG_SIGNING_KEY="0x1234567890ABCDEF"

Portage will only try to unlock the PGP private key at the beginning. If the user's key will expire over time, then consider enabling gpg-keepalive to prevent signing failures.

ARCHIVO /etc/portage/make.confEnabling Portage's gpg-keepalive feature
FEATURES="gpg-keepalive"

Poner en marcha un servidor de paquetes binarios

Portage ofrece el soporte de varios protocolos para la descarga de paquetes binarios: FTP, FTPS, HTTP, HTTPS y SSH. Esto deja espacio suficiente para muchas formas de implementación del servidor.

No hay sin embargo un método "listo para funcionar" que ofrezca Portage para la distribución de paquetes binarios. Dependiendo de la configuración deseada, será necesario instalar software adicional.

Servidor de paquetes binarios basado en Web

Una forma muy usada para la distribución de paquetes binarios es crear un servidor de paquetes basado en web.

HTTPD

Utilice un servidor web como lighttpd (www-servers/lighttpd) y configúrelo para ofrecer acceso de lectura a la localización definida en PKGDIR dentro del fichero /etc/portage/make.conf.

ARCHIVO /etc/lighttpd/lighttpd.confEjemplo de configuración lighttpd
# Añada esto al final de la configuración estándar
server.modules += ( "mod_alias" )
alias.url = ( "/packages" => "/usr/portage/packages/" )

Caddy

To set up the Caddy HTTP server to provide a web-based binary package host, create a Caddyfile containing:

ARCHIVO Caddyfile
x.x.x.x:80 { # Replace x.x.x.x with your host's IPv4 address
    root * /path/to/binhost/var/cache/binpkgs
    file_server browse # Needed to server 
}

Once that is created, run Caddy with:

root #caddy run --config /path/to/Caddyfile

A continuación, en los equipos cliente, configure la variable PORTAGE_BINHOST apropiadamente:

ARCHIVO /etc/portage/make.confUtilizar un servidor de paquetes binarios basado en web
PORTAGE_BINHOST="http://binhost.example.com/packages"

Equipo de paquetes binarios con SSH

Para ofrecer un enfoque con mayor autenticación para los paquetes binarios, se puede considerar el uso de SSH.

Cuando se utiliza SSH es posible utilizar la clave SSH del usuario root de Linux (sin frase contraseña ya que se necesita realizar la instalación en segundo plano) para conectar a un equipo remoto con los paquetes binarios.

Para conseguir esto, asegúrese de que se permite usar la clave SSH del usuario root en el servidor. Esto se debe realizar en cada máquina que se conectará al servidor de paquetes binarios que acepte SSH:

root #cat root.id_rsa.pub >> /home/binpkguser/.ssh/authorized_keys

La variable PORTAGE_BINHOST podría entonces parecerse a ésta:

ARCHIVO /etc/portage/make.confAjustar PORTAGE_BINHOST para acceso SSH
PORTAGE_BINHOST="ssh://usuariopqtbing@servidorbin/usr/portage/packages"

If the SSH server is listening to a different port (e.g 25), then it must be specified after the address, like so:

ARCHIVO /etc/portage/make.confSetting PORTAGE_BINHOST for SSH access on port 25
PORTAGE_BINHOST="ssh://binpkguser@binhostserver:25/var/cache/binpkgs"
Nota
No utilizzar los ficheros de configuración de SSH que se encuentran en ~/.ssh/config para definir puertos o el nombre del usuario. Esta localización se ignora cuando Portage intenta hacer rsync de los paquetes en el cliente. En lugar de esto, defina las opciones adecuadas en la variable PORTAGE_BINHOST.

Exportar mediante NFS

Cuando se utilizan paquetes binarios dentro de una red internt, puede que se más sencillo exportar los paquetes mediante NFS y montarlo en los clientes.

El fichero /etc/exports debería tener el siguiente aspecto:

ARCHIVO /etc/exportsExportar el directorio de paquetes
/usr/portage/packages   2001:db8:81:e2::/48(ro,no_subtree_check,root_squash) 192.168.100.1/24(ro,no_subtree_check,root_squash)

En los clientes, se puede ahora montar la localización. Un ejemplo de entrada /etc/fstab podría ser este:

ARCHIVO /etc/fstabEntrada para montar la carpeta que contiene los paquetes
binhost:/usr/portage/packages      /usr/portage/packages    nfs    defaults    0 0

The NFS share is mounted on the local filesystem, so there is no need to set PORTAGE_BINHOST or use the --getbinpkg option. Instead, follow the normal procedures for installing binary packages, remembering to point PKGDIR to the NFS share so that portage knows where to find the packages:

ARCHIVO /etc/portage/make.confSetting the package directory for portage
PKGDIR="/var/cache/binpkgs"
Nota
If PKGDIR is network-mounted, it may be advantageous to enable FEATURES="pkgdir-index-trusted". This feature disables checking the entire PKGDIR for added or removed packages and instead trusts the contents of the Packages file to be accurate. This significantly improves performance on high-latency networks.

Mantenimiento de paquetes binarios

Si la lista de paquetes binarios no se mantiene de forma activa, la exportación y distribución de paquetes binarios conllevará un consumo inútil de espacio de almacenamiento.

Eliminar paquetes binarios obsoletos

Como parte del paquete app-portage/gentoolkit, se ofrece una aplicación llamada eclean. Permite mantener ficheros variables relacionados con Portage como los ficheros de código fuente que se han descargado y también paquetes binarios.

La siguiente orden elimina todos los paquetes binarios que no tengan un ebuild correspondiente en los repositorios de ebuilds instalados:

root #eclean packages

Para más detalles, por favor, lea el artículo sobre eclean.

Otra herramienta que se puede utilizar es qpkg del paquete app-portage/portage-utils. Sin embargo, esta herramienta es menos configurable.

Para limpiar paquetes binarios no utilizados (en el sentido de que no los utiliza el servidor en el que se almacenan los paquetes binarios):

root #qpkg -c

Mantener el fichero Packages

Consejo
As of portage-3.0.52, Portage defaults to FEATURES=pkgdir-index-trusted for performance, which requires an accurate Packages index. This can be disabled if it is an inconvenience to regularly fix up the index with emaint after manual changes.

Dentro del directorio de paquetes hay un fichero manifiesto llamado Packages. Este fichero actúa como una caché de los metadatos de todos los paquetes binarios en el directorio de paquetes. Este fichero se actualiza cada vez que Portage agrega un paquete binario al directorio. Del mismo modo, eclean lo actualiza cuando elimina paquetes binarios.

Si por alguna razón los paquetes binarios se eliminan o copian en el directorio de paquetes o el fichero Packages se corrompe o se elimina, entonces se debe recrear. Esto se hace con la orden emaint:

root #emaint binhost --fix

To clear the cache of all binary packages:

root #rm -r /var/cache/binpkgs/*

Temas avanzados

Chrooting

If creating packages for a different Portage profile or system with different USE flags, a chroot can be created.

Nota
This example uses /var/chroot/buildenv as the chroot path, but any path can be used.

Creating the directories

First, the directories for this chroot must be created:

root #mkdir --parents /var/chroot/buildenv

Deploying the build environment

Next, the appropriate stage 3 tarball must be downloaded and extracted, here the desktop profile | openrc tarball is being used:

This can be extracted with the following command:

/var/chroot/buildenv/ #tar xpvf stage3-*.tar.xz --xattrs-include='*.*' --numeric-owner

Configuring the build environment

Importante
{{{1}}}

The build environment should be configured to match that of the system it is building for. The simplest way to do this is to copy the /etc/portage and /var/lib/portage/world files. This can be done with rsync:

Nota
This command should be executed on the build target machine, where the remote host has the chroot.
user $rsync --archive --whole-file --verbose /etc/portage/* larry@remote_host:/var/chroot/buildenv/etc/portage
user $rsync --archive --whole-file --verbose /var/db/repos/* larry@remote_host:/var/chroot/buildenv/var/db/repos
Nota
{{{1}}}

This process should be repeated for the world file:

user $rsync --archive --whole-file --verbose /var/lib/portage/world larry@remote_host:/var/chroot/buildenv/var/lib/portage/world
Nota
/var/lib/portage and /var/lib/portage/world should have the root:portage permissions.

Configuring the chroot

Once created, mounts must be bound for the chroot to work:

/var/chroot/buildenv #mount --types proc /proc proc
/var/chroot/buildenv #mount --rbind /dev dev
/var/chroot/buildenv #cp --dereference /etc/resolv.conf etc
Nota
If a tmpfs is being used for portage's temp dir, ensure that is mounted.

Entering the chroot

To enter this chroot, the following command can be used:

/var/chroot/buildenv #chroot . /bin/bash

Optionally, the prompt can be set to reflect the fact that the chroot is active:

/ #export PS1="(chroot) $PS1"
Performing an initial build
Nota
This step assumes this configuration has been completed: Setting portage to use buildpkg.

This step is optional, but rebuilds all packages in the new world:

(chroot) #emerge --emptytree @world

Building for other architectures

crossdev is a tool to easily build cross-compile toolchains. This is useful to create binary packages for installation on a system whose architecture differs from that of the system used to build the packages. A common example would be building binary packages for a device like an arm64 Raspberry Pi from a more powerful amd64 desktop PC.

An installation guide for sys-devel/crossdev can be found at the crossdev page.

Build a cross compiler

Using crossdev with the following command can build a toolchain for the desired system:

root #crossdev --stable -t <arch-vendor-os-libc>

For the rest of this section, the example target will be for a Raspberry Pi 4:

root #crossdev --stable -t aarch64-unknown-linux-gnu

After this has built, a toolchain will have been created in /usr/aarch64-unknown-linux-gnu, and will look like a bare-bones Gentoo install where it is possible to edit Portage settings as normal.

Consejo
Replacing aarch64-unknown-linux-gnu with aarch64-unknown-linux-musl would build a system with the Musl libc rather than Glibc.

Basic setup

Removing the -pam flag from the USE line in /usr/aarch64-unknown-linux-gnu/etc/portage/make.conf is generally recommended in a setup like this:

ARCHIVO /usr/aarch64-unknown-linux-gnu/etc/portage/make.confDisable the pam USE flag
CHOST=aarch64-unknown-linux-gnu
CBUILD=x86_64-pc-linux-gnu
 
ROOT=/usr/${CHOST}/
 
ACCEPT_KEYWORDS="${ARCH}"
 
USE="${ARCH}"
 
CFLAGS="-O2 -pipe -fomit-frame-pointer"
CXXFLAGS="${CFLAGS}"
 
FEATURES="-collision-protect sandbox buildpkg noman noinfo nodoc"
# Ensure pkgs from another repository are not overwritten
PKGDIR=${ROOT}var/cache/binpkgs/
 
#If you want to redefine PORTAGE_TMPDIR uncomment (and/or change the directory location) the following line
PORTAGE_TMPDIR=${ROOT}var/tmp/
 
PKG_CONFIG_PATH="${ROOT}usr/lib/pkgconfig/"
#PORTDIR_OVERLAY="/var/db/repos/local/"

Profiles

List available profiles for the device by running:

root #PORTAGE_CONFIGROOT=/usr/aarch64-unknown-linux-gnu eselect profile list

Next, select the profile that best suits:

root #PORTAGE_CONFIGROOT=/usr/aarch64-unknown-linux-gnu eselect profile set <profile number>

Build a single package

To build a single binary package for use on the device, use the following:

root #emerge-aarch64-unknown-linux-gnu --ask foo

Build world file

To build every package in the world file, then the following command is needed:

root #emerge-aarch64-unknown-linux-gnu --emptytree @world

Binary location

By default, all binary packages will be stored in /usr/aarch64-unknown-linux-gnu/var/cache/binpkgs, so this is the location needed to be selected when setting up a binary package host.

Crear instantáneas del directorio de paquetes

Cuando se despliegan paquetes binarios para un gran número de sistemas cliente podría resultar adecuado crear instantáneas del directorio de paquetes. Los sistemas cliente entonces no utilizan el directorio de paquetes directamente, sino que utilizan los paquetes binarios de la instantánea.

Se pueden crear las instantáneas usando la herramienta /usr/lib64/portage/python2.7/binhost-snapshot o la herramienta /usr/lib64/portage/python3.3/binhost-snapshot. Admiten cuatro argumentos:

  1. Un directorio fuente (el camino al directorio de paquetes).
  2. Un directorio destino (que no debe existir previamente).
  3. Un URI.
  4. Un directorio del servidor de paquetes binarios.

Los ficheros del directorio de paquetes se copian al directorio destino. Se crea entonces un fichero Packages dentro del directorio de paquetes binarios del servidor (el cuarto argumento) con el URI que se indica.

Los sistemas cliente necesitan utilizar un URI que apunta al directorio de paquetes binarios del servidor. A partir de ahí será redirigido al URI que se indicó a binhost-snapshot. Este URI tiene que hacer referencia al directorio destino.

Comprender el formato del paquete binario

XPAK format

El nombre de los paquetes binarios creados por Portage termina en .tbz2. Estos ficheros constan de dos partes:

  1. Un fichero .tar.bz2 que contiene los archivos que se van a instalar en el sistema
  2. Un fichero xpak que contiene los metadatos del paquete, el ebuild y el fichero de entorno.

La descripción del formato se puede leer en man xpak.

Hay algunas herramientas en app-portage/portage-utils que sirven para trocear o crear ficheros tbz2 y xpak.

La siguiente orden divide el fichero tbz2 en un fichero .tbz2 y en otro .xpak:

user $qtbz2 -s <paquete>.tbz2

El fichero .xpak se puede examinar con la utilidad qxpak.

Para listar los contenidos:

user $qxpak -l <paquete>.xpak

La siguiente orden extrae un fichero llamado USE que contiene los ajustes USE habilitados para este paquete:

user $qxpak -x package-manager-0.xpak USE

GPKG format

GPKG format binary packages created by Portage have the file name ending with .gpkg.tar. These files consist of four parts at least:

  1. A gpkg-1 empty file that used to identify the format.
  2. A C/PV/metadata.tar{.compression} archive containing package metadata, the ebuild, and the environment file.
  3. A C/PV/image.tar{.compression} archive containing the files that will be installed on the system.
  4. A Manifest file containing checksums to protect against file corruption.
  5. Multiple optional .sig files containing OpenPGP signature are used for integrity checking and verification of trust.

The format can be extracted by tar without the need for additional tools.

La plantilla PKGDIR

El formato de la versión que es el que se utiliza actualmente tiene la siguiente disposición:

CÓDIGO Plantilla de directorio de paquetes (version 2)
PKGDIR
`+- Packages
 +- app-accessibility/
 |  +- pkg1-version.tbz2
 |  `- pkgN-version.tbz2
 +- app-admin/
 |  `- ...
 `- ...

El fichero Packages es la principal mejora (y también el desencadenante de que Portage sepa que el directorio de paquete binario utiliza la versión 2) sobre la primera disposición de directorios de paquetes binarios (versión 1). En la versión 1, todos los paquetes binarios también se alojaban dentro de un único directorio (llamado All/) y los directorios de categoría contenían únicamente enlaces simbólicos a los paquetes binarios dentro del directorio All/.

In portage-3.0.15 and later, FEATURES=binpkg-multi-instance is enabled by default:

CÓDIGO Packages directory layout (version 2 + FEATURES=binpkg-multi-instance)
PKGDIR
`+- Packages
 +- app-accessibility/
 |  +- pkg1/
 |    +- pkg1-version-build_id.xpak
 |    `- pkgN-version-build_id.xpak
 +- app-admin/
 |  `- ...
 `- ...

Desempaquetar con quickunpkg

Zoobab ha escrito una sencilla herramienta de consola llamada quickunpkg para desempaquetar rápidamente ficheros tbz2.

See also

External resources

quickpkg man page.