Difference between revisions of "Funtoo:Metro/pt-br"

From Funtoo
Jump to navigation Jump to search
Line 152: Line 152:
== Passo 2: Compilando os stages pentium4 ==
== Passo 2: Compilando os stages pentium4 ==


À propósito, se tudo que você quis fazer até agora foi construir um novo stage1/2/3 funtoo-current (e também openvz e templates vserver). Você começaria o processo digitando:
A propósito, se tudo que você quis fazer até agora foi construir um novo stage1/2/3 funtoo-current (e templates openvz e vserver). Você começaria o processo digitando:


<console>
<console>

Revision as of 21:00, February 11, 2018

Other languages:
English • ‎Türkçe • ‎português do Brasil • ‎日本語

{{#layout:doc}}Metro é o sistema de compilação dos stages para Funtoo Linux e Gentoo Linux. Ele automatiza o processo de bootstrapping.

Este tutorial te guiará pela instalação, configuração e execução do Metro.

Outra Documentação do Metro está disponível.

Prefácio

Como o Metro Funciona

Metro é o sistema de compilação automatizado do Funtoo Linux, e é usado para compilar os stages do Funtoo Linux.

Metro não cria um stage do nada. Para compilar um novo stage, Metro deve usar um stage já existente chamado "seed" stage. Este seed stage tipicamente é usado como ambiente de compilação para criar o stage que queremos.

Metro pode usar dois tipos de seed stages. Tradicionalmente, Metro usa um stage3 como seed stage. Esse stage3 é então usado para compilar um novo stage1, que por sua vez é usado para compilar um novo stage2, e em seguida um novo stage3. No geral, este método é o mais confiável para compilação do Gentoo Linux ou Funtoo Linux, sendo assim essa é a abordagem recomendada.

   Important

Após trocar as compilações do metro para o perfil do Funtoo, os stages do Gentoo não serão mais fornecidos!

Seeds e Isolamento da Compilação

Outro conceito importante a se mencionar aqui é algo chamado isolamento de compilação. Pelo fato de o Metro criar um ambiente de compilação isolado, e esse ambiente é explicitamente definido usando entidades tangíveis e existentes -- um seed stage e um snapshot do portage -- você terá resultados consistentes e repetíveis. Em outras palavras, o mesmo seed stage, snapshot do portage e instruções de compilação irão gerar um resultado essencialmente idêntico, mesmo que você efetue a compilação um mês depois em outra máquina.

Compilação Local

Digamos que você queira compilar um stage3 para um pentium4. O método recomendado para fazer isso seria pegar um stage3 para pentium4 para usar como seu seed stage. Será dito ao Metro para usar este stage3 existente para compilar um novo stage1 para esse mesmo pentium4. Para esse processo, o stage3 genérico para pentium4 iria prover o ambiente de compilação para criar noss novo stage1. Então, o novo stage1 serviria de ambiente de compilação para criar o novo stage2 para pentium4. E o novo stage2 para pentium4 serviria de ambiente de compilação para criar o novo stage3 para pentium4.

Na terminologia do Metro isto é chamado de compilação local, que significa que um stage3 de uma dada arquitetura é usado para semear (seed) uma nova compilação dessa mesma arquitetura. A propósito, esse será o primeiro exercício que faremos nesse tutorial.

Uma semana depois, você pode querer compilar um novo stage3 para pentium4. Em vez de começar pelo stage3 original para pentium4 novamente, provavelmente você teria de configurar o Metro para usar a compilação mais recente do stage3 para pentium4 como seed. Metro tem uma funcionalidade embutida par facilitar isso, permitindo encontrar facilmente a versão mais recente do stage3 seed disponível.

Compilação Remota

Metro pode também realizar uma compilação remota, onde um stage3 de uma arquitetura diferente, porém com binários compatíveis,é usada como seed para compilar um stage3 de arquitetura diferente. Consequentemente o segundo exercício que iremos fazer neste tutorial será para compilar um stage3 para um core2 32bit a partir de um stage3 para pentium4 que acabamos de compilar.

TODO: adicionar embargos sobre quais arquiteturas podem ser semeadas (seeded) e quais não podem (uma tabela talvez?)

Compilação Adaptada

Por último, é também válido notar que tanto em compilações locais e remotas, Metro pode ser configurado para adicionar e/ou remover pacotes individuais do arquivo final. Digamos que você não viva sem app-misc/screen, no fim deste tutorial, iremos mostrar como ter seu stage3 adaptado para incluí-lo.

Instalando o Metro

O método recomendado e suportado é usar o repositório do Metro no Git.

Garanta que dev-vcs/git e No results (opcional; requerido para suporte a EC2) estão instalados em seu sistema:

root # emerge dev-vcs/git
root # emerge dev-python/boto

Em seguida, clone o o branch master do repositório desta maneira:

root # cd /root
root # git clone git://github.com/funtoo/metro.git
root # cp /root/metro/metro.conf ~/.metro

Agora você terá uma pasta chamada /root/metro que contém o código fonte do Metro.

Metro agora está instalado. É hora de customizá-lo para seu sistema local.

Configurando o Metro

   Note

Metro atualmente não pode compilar stages do Gentoo. Veja FL-901.

Daniel Robbins mantém o Metro, então ele vem pré-configurado para compilar lançamentos do Funtoo Linux. Antes de ler mais, você pode querer customizar algumas configurações básicas como o número de processos concorrentes que se ajustem ao seu hardware ou a pasta que receberá os stages produzidos. Isto é feito editando ~/.metro que é o arquivo mestre de configuração do Metro.

Note que path/install deve apontar para onde o metro foi instalado. Aponte path/distfiles para onde seus distfiles residem. Defina também path/mirror/owner e path/mirror/group para o proprietário e grupo de todos os arquivos que serão escritos na pasta de repositório de compilações, que por padrão (pelo arquivo de configuração) está em /home/mirror/funtoo. O diretório de cache normalmente reside dentro da pasta temp -- isso não pode ser modificado como quiser. O diretório de cache pode acabar tendo muitos pacotes .tbz2 armazenados, e consumir muito armazenamento. Você pode querer colocar o diretório temporário em um armazenamento mais rápido, para compilações mais rápidas, e o cache em um mais lento, porém com mais espaço.

   .metro - Metro configuration
# Main metro configuration file - these settings need to be tailored to your install:

[section path]
install: /root/metro
tmp: /var/tmp/metro
cache: $[path/tmp]/cache
distfiles: /var/src/distfiles
work: $[path/tmp]/work/$[target/build]/$[target/name]

[section path/mirror]

: /home/mirror/funtoo
owner: root
group: repomgr
dirmode: 775

[section portage]

MAKEOPTS: auto 

[section emerge]

options: --jobs=4 --load-average=4 --keep-going=n

# This line should not be modified:
[collect $[path/install]/etc/master.conf]

Arquitetura e Subarquitetura

No exemplo a seguir estaremos criando um stage3 para pentium4 compilado para compatibilidade binária com x86-32bit. Pentium4 é uma subarquitetura da arquitetura x86-32bit. Uma vez que você tenha o Metro instalado irá encontrar uma lista completa de cada subarquitetura na pasta /root/metro/subarch e cada uma terá a extensão .spec Exemplo:

root # ls /root/metro/subarch
root # ls subarch/
amd64-bulldozer-pure64.spec  armv7a.spec          core-avx-i.spec         i686.spec         pentium.spec
amd64-bulldozer.spec         armv7a_hardfp.spec   core2_32.spec           k6-2.spec         pentium2.spec
amd64-k10-pure64.spec        athlon-4.spec        core2_64-pure64.spec    k6-3.spec         pentium3.spec
amd64-k10.spec               athlon-mp.spec       core2_64.spec           k6.spec           pentium4.spec
amd64-k8+sse3.spec           athlon-tbird.spec    corei7-pure64.spec      native_32.spec    pentiumpro.spec
amd64-k8+sse3_32.spec        athlon-xp.spec       corei7.spec             native_64.spec    prescott.spec
amd64-k8-pure64.spec         athlon.spec          generic_32.spec         niagara.spec      ultrasparc.spec
amd64-k8.spec                atom_32.spec         generic_64-pure64.spec  niagara2.spec     ultrasparc3.spec
amd64-k8_32.spec             atom_64-pure64.spec  generic_64.spec         nocona.spec       xen-pentium4+sse3.spec
armv5te.spec                 atom_64.spec         generic_sparcv9.spec    opteron_64.spec   xen-pentium4+sse3_64.spec
armv6j.spec                  btver1.spec          geode.spec              pentium-m.spec
armv6j_hardfp.spec           btver1_64.spec       i486.spec               pentium-mmx.spec

Primeiros stages (compilação local)

Para iniciar todo o processo, precisamos fazer um bootstrap baixando um stage3 de seed para a compilação e colocá-lo em seu lugar adequado em /home/mirror/funtoo, assim o Metro pode encontrá-lo. Precisaremos também criar alguns arquivos "control" em /home/mirror/funtoo, que permitirá ao Metro entender como deve proceder.

Passo 1: Configurar o repositório pentium4 (compilação local)

Assumindo que estamos seguindo os passos básicos traçados na seção anterior, e criando uma compilação instável do Funtoo (funtoo-current) para pentium4, usando um stage3 pentium4 genérico como seed, então aqui está o primeiro conjunto de passos que faremos:

root # install -d /home/mirror/funtoo/funtoo-current/x86-32bit/pentium4
root # install -d /home/mirror/funtoo/funtoo-current/snapshots
root # cd /home/metro/mirror/funtoo/funtoo-current/x86-32bit/pentium4
root # install -d 2011-12-13
root # cd 2011-12-13
root # wget -c http://ftp.osuosl.org/pub/funtoo/funtoo-current/x86-32bit/pentium4/2011-12-13/stage3-pentium4-funtoo-current-2011-12-13.tar.xz
root # cd ..
root # install -d .control/version
root # echo "2011-12-13" > .control/version/stage3
root # install -d .control/strategy
root # echo local >  .control/strategy/build
root # echo stage3 > .control/strategy/seed

OK, vamos revisar os passos acima. Primeiro, criamos o diretório /home/mirror/funtoo/funtoo-current/x86-32bit/pentium4, que é onde o Metro espera encontrar as compilações instáveis do funtoo-current para pentium4 -- ele é configurado para procurar aqui por padrão. Então criamos um diretório nomeado especialmente para abrigar nosso stage3 de seed para x86. Novamente, por padrão, Metro espera que o diretório seja nomeado dessa maneira. Entramos neste diretório, e baixamos nosso seed x86 de funtoo.org. Note que o selo de versão 2010-12-24 confere. Certifique-se de que seu nome de diretório está de acordo com o nome do stage3 também. Tudo foi configurado para bater com a configuração padrão do layout de partições do Metro.

Agora, voltemos ao diretório /home/mirror/metro/funtoo-current/x86-32bit/pentium4 e, dentro dele, criaremos um diretório .control. Este diretório e seus subdiretórios contém arquivos especiais que o Metro referencia para determinar certos aspectos de seu comportamento. O arquivo .control/version/stage3 é usado pelo Metro para rastrear o stage3 mais recentemente compilado para esta compilação em particular e esta subarquitetura. O Metro vai automaticamente atualizar este arquivo com o selo de versão mais recente após ele ter compilado um novo stage3 com sucesso. Contudo pelo fato do Metro não ter compilado realmente este stage3, precisamos configurar o arquivo .control/version/stage3 manualmente. Isto possibilitará ao Metro encontrar nosso stage3 baixado quando configurarmos nossa compilação pentium4 para usá-lo como um seed. Perceba também que o Metro irá criar um arquivo similar ao .control/version/stage1 após compilar com sucesso um stage1 pentium4 funtoo-current.

Nós também configuramos os arquivos .control/strategy/build e .control/strategy/seed com os valores local e stage3 respectivamente. Estes arquivos definem a estratégia de compilação que o Metro usará quando compilarmos os stages pentium4 funtoo-current. Com uma nova estratégia de local, Metro irá suprir sua stage seed da funtoo-current pentium4, o diretório atual. E com uma estratégia de seed do stage3, o Metro usará um stage3 como seed, e usarará este seed para compilar um novo stage1, stage2 and stage3.

Passo 2: Compilando os stages pentium4

A propósito, se tudo que você quis fazer até agora foi construir um novo stage1/2/3 funtoo-current (e templates openvz e vserver). Você começaria o processo digitando:

root # cd /root/metro
root # scripts/ezbuild.sh funtoo-current pentium4

If you have a slow machine, it could take several hours to be completed because several "heavy" components like gcc or glibc have to be recompiled in each stage. Once a stage has been successfully completed, it is placed in the "${METRO_MIRROR}/funtoo-current/x32-bit/pentium4/YYYY-MM-DD" subdirectory, where YYYY-MM-DD is today's date at the time the ezbuild.sh script was started or the date you put on the ezscript.sh command line.

Building for another binary compatible architecture (remote build)

As written above, Metro is able to perform remote build building different architecture stage3 from a binary compatible seeding stage3 (e.g. using a pentium4 stage3 to seed a Intel Core2 32bits stage3).

In the Metro terminology this is called a remote build (a stage 3 of a different, but binary compatible, architecture is used as a seed). What's not compatible? You can't use a Sparc architecture to generate an x86 or ARM based stage and vice-versa. If you use a 32bit stage then you don't want to seed a 64bit build from it. Be sure that you are using a stage from the same architecture that you are trying to seed. Check Funtoo-current FTP Mirror for a stage that is from the same Architecture that you will be building.

   Note

Often, one build (ie. funtoo-current) can be used as a seed for another build such as funtoo-stable. However, hardened builds require hardened stages as seeds in order for the build to complete successfully.

Step 1: Set up Core_2 32bit repository

In this example, we're going to use this pentium4 funtoo-current stage3 to seed a new Core_2 32bit funtoo-current build. To get that done, we need to set up the pentium4 build directory as follows:

root #  cd /home/mirror/funtoo/funtoo-current/x86-32bit
root # install -d core2_32
root # cd core2_32
root # install -d .control/strategy
root # echo remote > .control/strategy/build
root # echo stage3 > .control/strategy/seed
root # install -d .control/remote
root # echo funtoo-current > .control/remote/build
root # echo x86-32bit > .control/remote/arch_desc
root # echo pentium4 > .control/remote/subarch

The steps we follow are similar to those we performed for a local build to set up our pentium4 directory for local build. However, note the differences. We didn't download a stage, because we are going to use the pentium4 stage to build a new Core_2 32bit stage. We also didn't create the .control/version/stage{1,3} files because Metro will create them for us after it successfully builds a new stage1 and stage3. We are still using a stage3 seed strategy, but we've set the build strategy to remote, which means that we're going to use a seed stage that's not from this particular subdirectory. Where are we going to get it from? The .control/remote directory contains this information, and lets Metro know that it should look for its seed stage3 in the /home/mirror/funtoo/funtoo-current/x86-32bit/pentium4 directory. Which one will it grab? You guessed it -- the most recently built stage3 (since our seed strategy was set to stage3) that has the version stamp of 2010-12-24, as recorded in /home/mirror/funtoo-current/x86-32bit/pentium4/.control/version/stage. Now you can see how all those control files come together to direct Metro to do the right thing.

   Note

arch_desc should be set to one of: x86-32bit, x86-64bit or pure64 for PC-compatible systems. You must use a 32-bit build as a seed for other 32-bit builds, and a 64-bit build as a seed for other 64-bit builds.

Step 2: Building the Core_2 32bit stages

Now, you could start building your new Core_2 32bit stage1/2/3 (plus openvz and vserver templates) by typing the following:

root # /root/metro/scripts/ezbuild.sh funtoo-current core2_32

In that case, the produced stages are placed in the /home/mirror/funtoo/funtoo-current/x32-bit/core2_32/YYYY-MM-DD subdirectory.

Step 3: The Next Build

At this point, you now have a new Core_2 32bit stage3, built using a "remote" pentium4 stage3. Once the first remote build completes successfully, metro will automatically change .control/strategy/build to be local instead of remote, so it will use the most recently-built Core_2 32bit stage3 as a seed for any new Core_2 32bit builds from now on.

Build your own tailored stage3

Metro can be easily configured for building custom stage3 by including additional packages. Edit the following configuration file /root/metro/etc/builds/funtoo-current/build.conf:

   funtoo-current/build.conf
[collect ../../fslayouts/funtoo/layout.conf]

[section release]

author: Daniel Robbins <drobbins@funtoo.org>

[section target]

compression: xz

[section portage]

FEATURES: 
SYNC: $[snapshot/source/remote]
USE:

[section profile]

format: new
path: gentoo:funtoo/1.0/linux-gnu
arch: $[:path]/arch/$[target/arch_desc]
build: $[:path]/build/current
flavor: $[:path]/flavor/core
mix-ins:

[section version]

python: 2.7

[section emerge]


[section snapshot]

type: live
compression: xz

[section snapshot/source]

type: git
branch: funtoo.org
# branch to have checked out for tarball:
branch/tar: origin/master
name: ports-2012 
remote: git://github.com/funtoo/ports-2012.git
options: pull

[section metro]

options: 
options/stage: cache/package
target: gentoo

[section baselayout]

services: sshd

[section multi]

snapshot: snapshot

[section files]

motd/trailer: [

 >>> Send suggestions, improvements, bug reports relating to...

 >>> This release:                  $[release/author]
 >>> Funtoo Linux (general):        Funtoo Linux (http://www.funtoo.org)
 >>> Gentoo Linux (general):        Gentoo Linux (http://www.gentoo.org)
]

[collect ../../multi-targets/$[multi/mode:zap]]

Building Gentoo stages

Metro can also build Gentoo stages. After switching to Funtoo profile, see http://www.funtoo.org/Funtoo_Profiles metro require additional steps for this. We have an open bug for this -- it is simply due to the fact that we focus on ensuring Funtoo Linux builds and building Gentoo is a lower priority. Historical note: Funtoo Linux originally started as a fork of Gentoo Linux so that metro could reliably build Gentoo stages. http://www.funtoo.org/Funtoo_Profiles

Advanced Features

Metro also includes a number of advanced features that can be used to automate builds and set up distributed build servers. These features require you to emerge sqlalchemy, as SQLite is used as a dependency.

Repository Management

Metro includes a script in the scripts directory called buildrepo. Buildrepo serves as the heart of Metro's advanced repository management features.

Initial Setup

To use buildrepo, you will first need to create a .buildbot configuration file. Here is the file I use on my AMD Jaguar build server:

   /root/.buildbot (python source code)
builds = (
	"funtoo-current",
	"funtoo-current-hardened",
	"funtoo-stable",
)

arches = (
	"x86-64bit",
	"pure64"
)

subarches = (
	"amd64-jaguar",
	"amd64-jaguar-pure64",
)

def map_build(build, subarch, full, full_date):
	# arguments refer to last build...
	if full == True:
		buildtype =  ( "freshen", )
	else:
		buildtype =  ("full", )
	return buildtype

This file is actually a python source file that defines the tuples builds, arches and subarches. These variables tell buildrepo which builds, arches and subarches it should manage. A map_build() function is also defined which buildbot uses to determine what kind of build to perform. The arguments passed to the function are based on the last successful build. The function can read these arguments and return a string to define the type of the next build. In the above example, the map_build() function will cause the next build after a freshen build to be a full build, and the next build after a full build to be a freshen build, so that the build will alternate between full and freshen.

Automated Builds

Once the .buildbot file has been created, the buildrepo and buildbot.sh tools are ready to use. Here's how they work. These tools are designed to keep your repository (path/mirror in /root/.metro up-to-date by inspecting your repository and looking for stages that are out-of-date.

To list the next build that will be performed, do this -- this is from my ARM build server:

root # ./buildrepo nextbuild
build=funtoo-current
arch_desc=arm-32bit
subarch=armv7a_hardfp
fulldate=2015-02-08
nextdate=2015-02-20
failcount=0
target=full
extras=''

If no output is displayed, then all your builds are up-to-date.

To actually run the next build, run buildbot.sh:

root # ./buildbot.sh

If you're thinking that buildbot.sh would be a good candidate for a cron job, you've got the right idea!

List Builds

To get a quick look at our repository, let's run the buildrepo fails command:

root # ./buildrepo fails
   0   2015-02-18 /home/mirror/funtoo/funtoo-current/x86-64bit/amd64-jaguar
   0   2015-02-18 /home/mirror/funtoo/funtoo-current/pure64/amd64-jaguar-pure64
   0   2015-02-18 /home/mirror/funtoo/funtoo-current-hardened/x86-64bit/amd64-jaguar
   0   2015-02-18 /home/mirror/funtoo/funtoo-current-hardened/pure64/amd64-jaguar-pure64
   0   2015-02-18 /home/mirror/funtoo/funtoo-stable/x86-64bit/amd64-jaguar
   0   2015-02-18 /home/mirror/funtoo/funtoo-stable/pure64/amd64-jaguar-pure64

On my AMD Jaguar build server, on Feb 20, 2015, this lists all the builds that buildrepo has been configured to manage. The first number on each line is a failcount, which is the number of consecutive times that the build has failed. A zero value indicates that everything's okay. The failcount is an important feature of the advanced repository management features. Here are a number of behaviors that are implemented based on failcount:

  • If buildbot.sh tries to build a stage and the build fails, the failcount is incremented.
  • If the build succeeds for a particular build, the failcount is reset to zero.
  • Builds with the lowest failcount are prioritized by Template:Buildrepo to build next, to steer towards builds that are more likely to complete successfully.
  • Once the failcount reaches 3 for a particular build, it is removed from the build rotation.

Resetting Failcount

If a build has issues, the failcount for a build will reach 3, at which point it will be pulled out of build rotation. To clear failcount, so that these builds are attempted again -- possibly fixed by new updates to the Portage tree -- use buildrepo zap:

root # /root/metro/scripts/buildrepo zap
Removing /mnt/data/funtoo/funtoo-current/arm-32bit/armv7a_hardfp/.control/.failcount...
Removing /mnt/data/funtoo/funtoo-current/arm-32bit/armv6j_hardfp/.control/.failcount...
Removing /mnt/data/funtoo/funtoo-current/arm-32bit/armv5te/.control/.failcount...

Repository Maintenance

A couple of repository maintenance tools are provided:

  • buildrepo digestgen will generate hash files for the archives in your repository, and clean up stale hashes.
  • buildrepo index.xml will create an index.xml file at the root of your repository, listing all builds available.
  • buildrepo clean will output a shell script that will remove old stages. No more than the three most recent stage builds for each build/arch/subarch are kept.

Distributed Repositories

In many situation, you will have a number of build servers, and each will build a subset of your master repository, and then upload builds to the master repository. This is an area of Metro that is being actively developed. For now, automated upload functionality is not enabled, but is expected to be implemented in the relatively near future. However, it is possible to have your master repository differentiate between subarches that are built locally, and thus should be part of that system's buildbot build rotation, and those that are stored locally and built remotely. These builds should be cleaned when buildrepo clean is run, but should not enter the local build rotation. To set this up, modify /root/.buildbot and use the subarches and all_subarches variables:

   /root/.metro - Excerpt of .metro config for master repository
# subarches we are building locally:

subarches = ( 
        "pentium4",
        "athlon-xp",
        "corei7",
        "corei7-pure64",
        "generic_32", 
        "i686", 
        "amd64-k8",
        "amd64-k8-pure64",
        "core2_64",
        "core2_64-pure64",
        "generic_64",
        "generic_64-pure64",
) 
  
# Things we need to clean, even if we may not be building:
  
all_subarches = subarches + (
        "atom_32",
        "atom_64",
        "atom_64-pure64",
        "amd64-k10",
        "amd64-k10-pure64",
        "amd64-bulldozer",
        "amd64-bulldozer-pure64",
        "amd64-steamroller",
        "amd64-steamroller-pure64",
        "amd64-piledriver",
        "amd64-piledriver-pure64",
        "amd64-jaguar",
        "amd64-jaguar-pure64",
        "intel64-haswell",
        "intel64-haswell-pure64",
        "intel64-ivybridge-pure64",
        "intel64-ivybridge",
        "armv7a_hardfp",
        "armv6j_hardfp",
        "armv5te"
)