Difference between pages "Install/ru/Partitioning" and "Metro Quick Start Tutorial/pt-br"

From Funtoo
< Install‎ | ru(Difference between pages)
Jump to navigation Jump to search
 
 
Line 1: Line 1:
<noinclude>
= Prefácio =  
{{InstallPart|процесс разбиения диска и создания файловых систем}}
</noinclude>
=== Подготовка жесткого диска ===


В этой части  мы научимся различным способам установки Funtoo Linux -- и загрузки с -- жесткого диска.
== Como o Metro Funciona ==


==== Введение ====
Você pode estar se perguntando como o [[Metro]] cria seu primeiro stage tarball. Como você pode ter imaginado, [[Metro]] não pode criar um stage tarball. Para construi um novo stage tarball, [[Metro]] deve utilizar um já existente, antigo stage tarball chamado de uma &quot;seed&quot; stage. Essa semente &quot;semente&quot; stage tipicamente é utilizado com o ''ambiente build'' para a criação do stage que queremos.


В прежние времена существовал лишь один способ загрузить PC-совместимый компьютер. Все наши дектопы и сервера имели стандартный PC BIOS, все наши харды использовали MBR и были разбиты используя схему разбивки MBR. Вот как это все было и нам это нравилось!
[[Metro]] pode utilizar dois tipos de semente stages. Tradicionalmente, [[Metro]] tem utilizado um stage3 como uma semente stage. Esse stage3 é então utilizado para construir um novo stage1, que em troca é utlilizado para construir um novo stage2, e então um novo stage3. Esse é geralmente o jeito mais confiável de construir [[Gentoo Linux]] ou [[Funtoo Linux]], entao essa é a recomendação recomendada.
{{fancyimportant|'''Depois de portar o metro builds para o perfil do Funtoo, os stages do Gentoo não são mais fornecidos'''!}}


Затем появились EFI и UEFI,  встроенные программы нового образца наряду со схемой разбивки GPT, поддерживающая диски размером более 2.2TБ. Неожиданно, нам стали доступны различные способы установки и загрузки Линукс систем . То, что было единым методом, стало чем-то более сложным.
== Sementes e Build Isolation ==


Воспользуемся моментом и рассмотрим доступные способы конфигурации жесткого диска для загрузки Funtoo Linux. Данное Руководство рекомендует способ "по-старинке" , загрузка BIOS и использование MBR. Данный способ работает (за исключением редких случаев) и всесторонне поддерживается. И в этом нет ничего плохого. Если Ваш жесткий диск 2TБ или меньшего размера это не является препятствием для использования всего дискового пространства.
Um outro conceito importante a mencionar aqui é algo chamando de ''build isolation''. Por que o [[Metro]] cria um ambiente build isolado, e o ambiente build é explicitamente definido utilizando entidades existentes, tangíveis -- uma semente stage e um portage snapshot -- você obterá resultados consistentes, repetíveis. Em outras palavras, a mesma semente stage, portage snapshot e instrções build gerarão resultados identico, mesmo se você desempenhar o um mês mais tarde em algum workstation de outro pessoa.


Но, бывают ситуации когда метод "по-старинке"  не является оптимальным. Если Ваш жесткий диск размером более 2TБ , MBR разбивка не сможет обеспечить доступ ко всему дисковому пространству.  Это одна из причин.  Вторая причина: существуют  "PC" системы, которые более не поддерживают  BIOS загрузку  и  форсируют UEFI загрузку. Из чувства сострадания к тем, кто попал в затруднение перед выбором, это Руководство также описывает установку и загрузку UEFI систем.
== Local Build ==


Мы всё же рекомендуем разбивку "по-старинке". Загрузчик, который мы используем для загрузки Линукс в этом руководстве называется GRUB,  таки образом мы называем метод  как '''BIOS + GRUB (MBR)''' . Это традиционный способ установки на PC-совместимые компьютеры.
Digamos que você queira construir um novo tarball stage3 <tt>pentium4</tt>. O módo recomendado de se fazer isso seria apanhar um tarball stage3 <tt>pentium4</tt> existente como sua semente stage3 stage. Será dito ao [[Metro]] utilizar o stage3 <tt>pentium4</tt> existente para construir um novo stage1 para o mesmo <tt>pentium4</tt>. Para esse process, o stage3 para o <tt>pentium4</tt> genérico forneceria o ''ambiente build'' para a criação de nosso novo stage1. Então, o novo stage1 serviria como o ambiente build (build environment) para a criação do novo stage2 <tt>pentium4</tt>. E o novo stage2 para <tt>pentium4</tt> serviria como o ambiente build para a criação do novo stage3 para <tt>pentium4</tt>.


Если Вам необходимо использование UEFI для загрузки, мы советуем не использовать MBR вообще, ввиду того, что некоторые системы поддерживают MBR,  а некоторые нет. Вместо, мы советуем использование UEFI  для загрузки GRUB, который, затем в свою очередь загрузит Линукс. Мы называем этот  метод как '''UEFI + GRUB (GPT)'''.
Na terminologia [[Metro]] isso é chamado de um '''local build''', que significa que um stage3 de uma dada arquitetura é utilizada para semear um build novo em folha da mesma arquitetura. Incidentalmente esse será o primeiro exercício que vamos realizar nesse tutorial.


И да, есть еще несколько способов, некоторые из них задокументированы в [[Boot Methods]] . Обычно мы рекомендуем  '''BIOS + GRUB (GPT)''' метод, но он ограничивается не столь широкой поддержкой со стороны комплектующих.
Uma semana depois, você pode querer construir um tarball stage3 para <tt>pentium4</tt> novo em folha. Ao invés de iniciar a partir do stage3 para <tt>pentium4</tt> original de novo, você provavelmente configuraria o [[Metro]] para utilizar o built stage3 para <tt>pentium4</tt> mais recente construído como a semente. [[Metro]] possui funcionalidade built-in para tornar isso fácil, permitindo facilmente encontrar e rastrear a semente stage3 mais recente disponível.


'''Вопрос --  какой из методов использовать?'''  Вот какой.
== Build Remoto ==


;Принцип 1 - "По-старинке":  Если Вы можете успешно загрузить System Rescue CD и видите синее меню, то Вы используете BIOS, и скорее всего Вы можете загрузить Funtoo Linux используя BIOS. Итак, следуйте этому способу и используйте BIOS загрузку,  кроме случаев Вам по-какой либо причине необходим UEFI, например если размер жесткого диска >2.2TБ.  В этом случае следуйте Принцип  2.
[[Metro]] pode também desempenhar '''build remoto (remote build)''', onde um stage3 de uma arquitetura diferente, mas compatível binariamente, é utilizado como uma semente para construir um stage3 de arquitetura diferente. Consequencialidade, no segundo exercício que vamos realizar nesse tutorial será construir um tarball stage3 para <tt>core2 32bit</tt> a partir do tarball stage3 do <tt>pentium4</tt> que acabamos de construir.


;Принцип 2 - "Модерн"Если Вы можете успешно загрузить System Rescue CD и видите черно-белое меню -- поздравления,  Ваша система поддерживает UEFI загрузку. Это значит, что Вы готовы установить Funtoo Linux к загрузке с помощью UEFI.  Ваша система также может поддерживать загрузку BIOS,  но попрбуйте UEFI для начала. Вы можете "покопаться" в настройках BIOS.
TODO: adicione ressalvas a respeito de quais arquiteturas podem ser semeadas e quais não podem (talvez um table?)


;Какая разница между "По-старинке" и "Модерн"?:  Если Вы следуете  MBR разбивке, Ваш <code>/boot</code> раздел будет отформатирован файловой системой ext2 , и Вы будете использовать <code>fdisk</code> для создания MBR разделов.  Если Вы следуете "модерн", GPT разделам и UEFI загрузке,  Ваш <code>/boot</code> раздел будет отформатирован  в файловую систему vfat,  поскольку это единственная файловая система поддерживаемая UEFI, и Вы будете использовать <code>gdisk</code> для создания GPT разделов.  И Вы установите GRUB несколько иначе.  Вот к чему сводится различие между методами.
== Build Adaptado ==


;Имейте в виду: Для установки Funtoo Linux используя метод "модерн", Вы должны загрузить System Rescue CD в UEFI режиме -- и увидеть начальное черно-белое меню. В противном случае, UEFI не активно и Вы не сможете продолжить!
Por ultimo, também é válido tanto <tt>local</tt> e <tt>builds remotos</tt>, [[Metro]] pode ser configurado para adicionar e/ou remover pacotes individuais ao ultimo tarball.
Digamos que você não consiga viver sem <tt>app-misc/screen</tt>, no final desse tutorial, mostraremos como obter o seu stage3 adaptado para incluí-lo.


{{Note|'''Некоторые материнские платы якобы поддерживают UEFI, но на самом деле нет.''' Исследуйте . К примеру,  Award BIOS в моей Gigabyte GA-990FXA-UD7 rev 1.1 имеет возможность включить UEFI загрузку для CD/DVD. '''Этого не достаточно для обеспечения UEFI загрузки для жестких дисков и установки Funtoo Linux.''' UEFI должно поддерживать и сьемные носители (таким образом Вы сможете загрузить System Rescue CD используя  UEFI) и жесткие диски (Вы можете загрузить Funtoo Linux.) Оказывается, что более поздние ревизии этой платы (rev 3.0) имеют новую версию BIOS который полностью поддерживает UEFI.  Это приводит к третьему принципу -- знайте Ваши комплектующие.}}
== Instalar o Metro ==


==== Метод (BIOS/MBR) "По-старинке" ====
'''O método recomendado e que possui suporte''' é utilizar o repositório Git do [[Metro]]. 


{{Note|Используйте данный метод при загрузке с помощью BIOS,  и если System Rescue CD имеет начальное меню загрузки светло-голубое.  Если Вы собираетесь использовать "модерн", [[#Метод (UEFI/GPT) "Модерн"|кликните здесь в меню UEFI/GPT.]]}}
Asegure-se de que {{Package|dev-vcs/git}} e {{Package|dev-python/boto}} (opcional; exigido para suporte EC2) sejam estalados no seu sistema:


===== Подготовка =====
<console>
# ##i##emerge dev-vcs/git
# ##i##emerge dev-python/boto
</console>


Прежде чем начать , неплохо бы удостовериться, что Вы используете нужный диск для разбивки.  Попробуйте эту комманду и проверьте, что <code>/dev/sda</code> тот самый диск, который Вы желаете разбить:
Depois, clone o master git repository como a seguir:


<console>
<console>
# ##i##fdisk -l /dev/sda
# ##i##cd /root
# ##i##git clone git://github.com/funtoo/metro.git
# ##i##cp /root/metro/metro.conf ~/.metro
</console>
 
Agora você terá o diretório chamado <tt>/root/metro</tt> que contem todo o código fonte do [[Metro]].


Disk /dev/sda: 640.1 GB, 640135028736 bytes, 1250263728 sectors
O Metro agora está instalado. É hora de personalizá-lo para o seu sistema local.
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk label type: gpt


= Configuring Metro =


#        Start          End    Size  Type            Name
{{Note|Metro não é atualmente capaz de construir stages do Gentoo. Veja {{Bug|FL-901}}.}}
1        2048  1250263694  596.2G  Linux filesyste Linux filesystem
</console>


Теперь, рекомендуем стереть  существующие таблицы разделов  MBR или GPT, которые могут помешать BIOS во время загрузки. Мы используем комманду <code>sgdisk</code>:
[[User:Drobbins|Daniel Robbins]] mantem o  [[Metro]], então ele vem pré-configurado para construir com sucesso os lançamentos do [[Funtoo Linux]]. Antes de ler mais adiante, você pode querer personalizar algumas configurações básicas como o o número de de jobs simultâneos para se encaixar as compatibilidades do seu hardware ou o diretório para utilizar arquivos stage produzidos. Isso é excelente ao editar <tt>~/.metro</tt> a qual é o arquivo de configuração [[Metro]]'s master.
{{fancywarning|Это необратимый процесс, который уничтожит все разделы!  Вы предупреждены! Советуем сохранить критические данние перед этим.}}


<console>
Por favor, note que o <code>path/install</code> deve apontar para aonde o metro foi instalado. Aponte <code>path/distfiles</code> para aonde seus distfiles residem. Defina também  <code>path/mirror/owner</code> e <code>path/mirror/group</code> para o proprietário e grupo de todos os arquivos que serão escritos para construir o diretório do repositório, which by default (as per the configuration file) is at <code>/home/mirror/funtoo</code>. The cache directory normally resides inside the temp directory -- this can be modified as desired. The cache directory can end up holding many cached .tbz2 packages, and eat up a lot of storage. You may want to place the temp directory on faster storage, for faster compile times, and place the cache directory on slower, but more plentiful storage.
# ##i##sgdisk --zap-all /dev/sda


Creating new GPT entries.
{{file|name=.metro|desc=Metro configuration|body=
GPT data structures destroyed! You may now partition the disk using fdisk or
# Main metro configuration file - these settings need to be tailored to your install:
other utilities.
</console>


Не стоит беспокоится об этом сообщении, так как комманда успешно выполнена:
[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]


<console>
[section path/mirror]
***************************************************************
Found invalid GPT and valid MBR; converting MBR to GPT format
in memory.
***************************************************************
</console>


===== Разбивка диска =====
: /home/mirror/funtoo
owner: root
group: repomgr
dirmode: 775


Теперь мы используем <code>fdisk</code> для создания таблицы разделов MBR и самих разделов:
[section portage]


<console>
MAKEOPTS: auto
# ##i##fdisk /dev/sda
</console>


В консоли <code>fdisk</code>, следуйте следующим шагам:
[section emerge]


'''Очистить таблицу разделов''':
options: --jobs=4 --load-average=4 --keep-going=n


<console>
# This line should not be modified:
Command (m for help): ##i##o ↵
[collect $[path/install]/etc/master.conf]
</console>
}}


'''Создать раздел 1''' (boot):
== Arch and Subarch ==


In the following example we are creating a pentium4 stage 3 compiled for x86-32bit binary compatibility. Pentium4 is a subarch of the x86-32bit architecture. Once you have metro installed you may find a full list of each subarch in your <tt>/root/metro/subarch</tt> directory each subarch will have the file extension .spec
Example:
<console>
<console>
Command (m for help): ##i##n ↵
###i## ls /root/metro/subarch
Partition type (default p): ##i##↵
# ls subarch/
Partition number (1-4, default 1): ##i##↵
amd64-bulldozer-pure64.spec  armv7a.spec          core-avx-i.spec        i686.spec        pentium.spec
First sector: ##i##↵
amd64-bulldozer.spec        armv7a_hardfp.spec  core2_32.spec          k6-2.spec        pentium2.spec
Last sector: ##i##+128M ↵
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
</console>
</console>


'''Создать раздел 2''' (своп):
= First stages build (local build) =
 
To get this all started, we need to bootstrap the process by downloading an initial seed stage3 to use for building and place it in its proper location in <tt>/home/mirror/funtoo</tt>, so that [[Metro]] can find it. We will also need to create some special &quot;control&quot; files in <tt>/home/mirror/funtoo</tt>, which will allow [[Metro]] to understand how it is supposed to proceed.


<console>
== Step 1: Set up pentium4 repository (local build) ==
Command (m for help): ##i##n ↵
Partition type (default p): ##i##↵
Partition number (2-4, default 2): ##i##↵
First sector: ##i##↵
Last sector: ##i##+2G ↵
Command (m for help): ##i##t ↵
Partition number (1,2, default 2): ##i## ↵
Hex code (type L to list all codes): ##i##82 ↵
</console>


'''Создать корневой раздел:'''
Assuming we're following the basic steps outlined in the previous section, and building an unstable funtoo (<tt>funtoo-current</tt>) build for the <tt>pentium4</tt>, using a generic <tt>pentium4</tt> stage3 as a seed stage, then here the first set of steps we'd perform:


<console>
<console>
Command (m for help): ##i##n ↵
# ##i##install -d /home/mirror/funtoo/funtoo-current/x86-32bit/pentium4
Partition type (default p): ##i##
# ##i##install -d /home/mirror/funtoo/funtoo-current/snapshots
Partition number (3,4, default 3): ##i##
# ##i##cd /home/metro/mirror/funtoo/funtoo-current/x86-32bit/pentium4
First sector: ##i##
# ##i##install -d 2011-12-13
Last sector: ##i##
# ##i##cd 2011-12-13
# ##i##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
# ##i##cd ..
# ##i##install -d .control/version
# ##i##echo "2011-12-13" > .control/version/stage3
# ##i##install -d .control/strategy
# ##i##echo local >  .control/strategy/build
# ##i##echo stage3 > .control/strategy/seed
</console>
</console>


'''Проверить таблицу разделов:'''
OK, let's review the steps above. First, we create the directory <tt>/home/mirror/funtoo/funtoo-current/x86-32bit/pentium4</tt>, which is where Metro will expect to find unstable <tt>funtoo-current</tt> pentium4 builds -- it is configured to look here by default. Then we create a specially-named directory to house our seed x86 stage3. Again, by default, Metro expects the directory to be named this way. We enter this directory, and download our seed x86 stage3 from funtoo.org. Note that the <tt>2010-12-24</tt> version stamp matches. Make sure that your directory name matches the stage3 name too. Everything has been set up to match Metro's default filesystem layout.


<console>
Next, we go back to the <tt>/home/mirror/metro/funtoo-current/x86-32bit/pentium4</tt> directory, and inside it, we create a <tt>.control</tt> directory. This directory and its subdirectories contain special files that Metro references to determine certain aspects of its behavior. The <tt>.control/version/stage3</tt> file is used by Metro to track the most recently-built stage3 for this particular build and subarch. Metro will automatically update this file with a new version stamp after it successfully builds a new stage3. But because Metro didn't actually ''build'' this stage3, we need to set up the <tt>.control/version/stage3</tt> file manually. This will allow Metro to find our downloaded stage3 when we set up our pentium4 build to use it as a seed. Also note that Metro will create a similar <tt>.control/version/stage1</tt> file after it successfully builds an pentium4 funtoo-current stage1.
Command (m for help): ##i##p


Disk /dev/sda: 298.1 GiB, 320072933376 bytes, 625142448 sectors
We also set up <tt>.control/strategy/build</tt> and <tt>.control/strategy/seed</tt> files with values of <tt>local</tt> and <tt>stage3</tt> respectively. These files define the building strategy Metro will use when we build pentium4 funtoo-current stages. With a build strategy of <tt>local</tt>, Metro will source its seed stage from funtoo-current pentium4, the current directory. And with a seed strategy of <tt>stage3</tt>, Metro will use a stage3 as a seed, and use this seed to build a new stage1, stage2 and stage3.
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x82abc9a6


Device    Boot    Start      End    Blocks  Id System
== Step 2: Building the pentium4 stages ==
/dev/sda1          2048    264191    131072  83 Linux
/dev/sda2        264192  4458495  2097152  82 Linux swap / Solaris
/dev/sda3        4458496 625142447 310341976  83 Linux
</console>


'''Записать таблицу разделов на диск:'''
Incidentally, if all you wanted to do at this point was to build a new pentium4 funtoo-current stage1/2/3 (plus openvz and vserver templates). You would begin the process by typing:


<console>
<console>
Command (m for help): ##i##w
# ##i##cd /root/metro
# ##i##scripts/ezbuild.sh funtoo-current pentium4
</console>
</console>


Ваша новая таблица разделов будет записана на диск.
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 <tt>"${METRO_MIRROR}/funtoo-current/x32-bit/pentium4/YYYY-MM-DD"</tt> subdirectory, where <tt>YYYY-MM-DD</tt> is today's date at the time the <tt>ezbuild.sh</tt> 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 <tt>Intel Core2 32bits</tt> stage3).  


{{Note|Вы зершили создание разделов! Теперь, перейдите к  [[#Создание файловых систем|Создание файловых систем]].}}
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 <tt>Sparc</tt> architecture to generate an <tt>x86</tt> or <tt>ARM</tt> 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 [http://ftp.osuosl.org/pub/funtoo/funtoo-current/ Funtoo-current FTP Mirror] for a stage that is from the same Architecture that you will be building.


==== New-School (UEFI/GPT) Method ====
{{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.}}


{{Note|Use this method if you are booting using UEFI, and if your System Rescue CD initial boot menu was black and white. If it was light blue, this method will not work.}}
== Step 1: Set up Core_2 32bit repository ==


The <tt>gdisk</tt> commands to create a GPT partition table are as follows. Adapt sizes as necessary, although these defaults will work for most users. Start <code>gdisk</code>:
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:


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


Within <tt>gdisk</tt>, follow these steps:
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 <tt>.control/version/stage{1,3}</tt> files because Metro will create them for us after it successfully builds a new stage1 and stage3. We are still using a <tt>stage3</tt> seed strategy, but we've set the build strategy to <tt>remote</tt>, 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 <tt>.control/remote</tt> directory contains this information, and lets Metro know that it should look for its seed stage3 in the <tt>/home/mirror/funtoo/funtoo-current/x86-32bit/pentium4</tt> directory. Which one will it grab? You guessed it -- the most recently built ''stage3'' (since our seed strategy was set to <tt>stage3</tt>) that has the version stamp of <tt>2010-12-24</tt>, as recorded in <tt>/home/mirror/funtoo-current/x86-32bit/pentium4/.control/version/stage</tt>. Now you can see how all those control files come together to direct Metro to do the right thing.


'''Create a new empty partition table''' (This ''will'' erase all data on the disk when saved):
{{Note|<code>arch_desc</code> should be set to one of: <code>x86-32bit</code>, <code>x86-64bit</code> or <code>pure64</code> 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.}}


<console>
== Step 2: Building the Core_2 32bit stages ==
Command: ##i##o ↵
This option deletes all partitions and creates a new protective MBR.
Proceed? (Y/N): ##i##y ↵
</console>


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


<console>
<console>
Command: ##i##n ↵
# ##i##/root/metro/scripts/ezbuild.sh funtoo-current core2_32
Partition Number: ##i##1 ↵
First sector: ##i##↵
Last sector: ##i##+500M ↵
Hex Code: ##i##
</console>
</console>


'''Create Partition 2''' (swap):
In that case, the produced stages are placed in the <tt>/home/mirror/funtoo/funtoo-current/x32-bit/core2_32/YYYY-MM-DD</tt> subdirectory.
 
<console>
Command: ##i##n ↵
Partition Number: ##i##2 ↵
First sector: ##i##↵
Last sector: ##i##+4G ↵
Hex Code: ##i##8200 ↵
</console>


'''Create Partition 3''' (root):
== Step 3: The Next Build ==


<console>
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 <code>.control/strategy/build</code> to be <code>local</code> instead of <code>remote</code>, 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.
Command: ##i##n ↵
Partition Number: ##i##3 ↵
First sector: ##i##↵
Last sector: ##i##↵##!i## (for rest of disk)
Hex Code: ##i##↵
</console>


Along the way, you can type "<tt>p</tt>" and hit Enter to view your current partition table. If you make a mistake, you can type "<tt>d</tt>" to delete an existing partition that you created. When you are satisfied with your partition setup, type "<tt>w</tt>" to write your configuration to disk:
= Build your own tailored stage3 =


'''Write Partition Table To Disk''':
Metro can be easily configured for building custom stage3 by including additional packages. Edit the following configuration file <tt>/root/metro/etc/builds/funtoo-current/build.conf</tt>:
{{file|name=funtoo-current/build.conf|body=
[collect ../../fslayouts/funtoo/layout.conf]


<console>
[section release]
Command: ##i##w ↵
Do you want to proceed? (Y/N): ##i##Y ↵
</console>


The partition table will now be written to disk and <tt>gdisk</tt> will close.
author: Daniel Robbins <drobbins@funtoo.org>


Now, your GPT/GUID partitions have been created, and will show up as the following ''block devices'' under Linux:
[section target]


* <tt>/dev/sda1</tt>, which will be used to hold the <tt>/boot</tt> filesystem,
compression: xz
* <tt>/dev/sda2</tt>, which will be used for swap space, and
* <tt>/dev/sda3</tt>, which will hold your root filesystem.


==== Creating filesystems ====
[section portage]


{{Note|This section covers both BIOS ''and'' UEFI installs. Don't skip it!}}
FEATURES:
SYNC: $[snapshot/source/remote]
USE:


Before your newly-created partitions can be used, the block devices need to be initialized with filesystem ''metadata''. This process is known as ''creating a filesystem'' on the block devices. After filesystems are created on the block devices, they can be mounted and used to store files.
[section profile]


Let's keep this simple. Are you using old-school MBR partitions? If so, let's create an ext2 filesystem on /dev/sda1:
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:


<console>
[section version]
# ##i##mkfs.ext2 /dev/sda1
</console>


If you're using new-school GPT partitions for UEFI, you'll want to create a vfat filesystem on /dev/sda1, because this is what UEFI is able to read:
python: 2.7


<console>
[section emerge]
# ##i##mkfs.vfat -F 32 /dev/sda1
</console>


Now, let's create a swap partition. This partition will be used as disk-based virtual memory for your Funtoo Linux system.


You will not create a filesystem on your swap partition, since it is not used to store files. But it is necessary to initialize it using the <code>mkswap</code> command. Then we'll run the <code>swapon</code> command to make your newly-initialized swap space immediately active within the live CD environment, in case it is needed during the rest of the install process:
[section snapshot]


<console>
type: live
# ##i##mkswap /dev/sda2
compression: xz
# ##i##swapon /dev/sda2
</console>


Now, we need to create a root filesystem. This is where Funtoo Linux will live. We generally recommend ext4 or XFS root filesystems. If you're not sure, choose ext4. Here's how to create a root ext4 filesystem:
[section snapshot/source]


<console>
type: git
# ##i##mkfs.ext4 /dev/sda3
branch: funtoo.org
</console>
# branch to have checked out for tarball:
branch/tar: origin/master
name: ports-2012
remote: git://github.com/funtoo/ports-2012.git
options: pull


...and here's how to create an XFS root filesystem, if you choose to use XFS:
[section metro]


<console>
options:
# ##i##mkfs.xfs /dev/sda3
options/stage: cache/package
</console>
target: gentoo


Your filesystems (and swap) have all now been initialized, so that that can be mounted (attached to your existing directory heirarchy) and used to store files. We are ready to begin installing Funtoo Linux on these brand-new filesystems.
[section baselayout]


{{fancywarning|1=
services: sshd
When deploying an OpenVZ host, please use ext4 exclusively. The Parallels development team tests extensively with ext4, and modern versions of <code>openvz-rhel6-stable</code> are '''not''' compatible with XFS, and you may experience kernel bugs.
}}


==== Mounting filesystems ====
[section multi]


Mount the newly-created filesystems as follows, creating <code>/mnt/funtoo</code> as the installation mount point:
snapshot: snapshot


<console>
[section files]
# ##i##mkdir /mnt/funtoo
# ##i##mount /dev/sda3 /mnt/funtoo
# ##i##mkdir /mnt/funtoo/boot
# ##i##mount /dev/sda1 /mnt/funtoo/boot
</console>


Optionally, if you have a separate filesystem for <code>/home</code> or anything else:
motd/trailer: [


<console>
>>> Send suggestions, improvements, bug reports relating to...
# ##i##mkdir /mnt/funtoo/home
# ##i##mount /dev/sda4 /mnt/funtoo/home
</console>


If you have <code>/tmp</code> or <code>/var/tmp</code> on a separate filesystem, be sure to change the permissions of the mount point to be globally-writeable after mounting, as follows:
>>> This release:                  $[release/author]
>>> Funtoo Linux (general):        Funtoo Linux (http://www.funtoo.org)
>>> Gentoo Linux (general):        Gentoo Linux (http://www.gentoo.org)
]


<console>
[collect ../../multi-targets/$[multi/mode:zap]]
# ##i##chmod 1777 /mnt/funtoo/tmp
}}
</console>

Revision as of 10:58, January 15, 2015

Prefácio

Como o Metro Funciona

Você pode estar se perguntando como o Metro cria seu primeiro stage tarball. Como você pode ter imaginado, Metro não pode criar um stage tarball. Para construi um novo stage tarball, Metro deve utilizar um já existente, antigo stage tarball chamado de uma "seed" stage. Essa semente "semente" stage tipicamente é utilizado com o ambiente build para a criação do stage que queremos.

Metro pode utilizar dois tipos de semente stages. Tradicionalmente, Metro tem utilizado um stage3 como uma semente stage. Esse stage3 é então utilizado para construir um novo stage1, que em troca é utlilizado para construir um novo stage2, e então um novo stage3. Esse é geralmente o jeito mais confiável de construir Gentoo Linux ou Funtoo Linux, entao essa é a recomendação recomendada.

   Important

Depois de portar o metro builds para o perfil do Funtoo, os stages do Gentoo não são mais fornecidos!

Sementes e Build Isolation

Um outro conceito importante a mencionar aqui é algo chamando de build isolation. Por que o Metro cria um ambiente build isolado, e o ambiente build é explicitamente definido utilizando entidades existentes, tangíveis -- uma semente stage e um portage snapshot -- você obterá resultados consistentes, repetíveis. Em outras palavras, a mesma semente stage, portage snapshot e instrções build gerarão resultados identico, mesmo se você desempenhar o um mês mais tarde em algum workstation de outro pessoa.

Local Build

Digamos que você queira construir um novo tarball stage3 pentium4. O módo recomendado de se fazer isso seria apanhar um tarball stage3 pentium4 existente como sua semente stage3 stage. Será dito ao Metro utilizar o stage3 pentium4 existente para construir um novo stage1 para o mesmo pentium4. Para esse process, o stage3 para o pentium4 genérico forneceria o ambiente build para a criação de nosso novo stage1. Então, o novo stage1 serviria como o ambiente build (build environment) para a criação do novo stage2 pentium4. E o novo stage2 para pentium4 serviria como o ambiente build para a criação do novo stage3 para pentium4.

Na terminologia Metro isso é chamado de um local build, que significa que um stage3 de uma dada arquitetura é utilizada para semear um build novo em folha da mesma arquitetura. Incidentalmente esse será o primeiro exercício que vamos realizar nesse tutorial.

Uma semana depois, você pode querer construir um tarball stage3 para pentium4 novo em folha. Ao invés de iniciar a partir do stage3 para pentium4 original de novo, você provavelmente configuraria o Metro para utilizar o built stage3 para pentium4 mais recente construído como a semente. Metro possui funcionalidade built-in para tornar isso fácil, permitindo facilmente encontrar e rastrear a semente stage3 mais recente disponível.

Build Remoto

Metro pode também desempenhar build remoto (remote build), onde um stage3 de uma arquitetura diferente, mas compatível binariamente, é utilizado como uma semente para construir um stage3 de arquitetura diferente. Consequencialidade, no segundo exercício que vamos realizar nesse tutorial será construir um tarball stage3 para core2 32bit a partir do tarball stage3 do pentium4 que acabamos de construir.

TODO: adicione ressalvas a respeito de quais arquiteturas podem ser semeadas e quais não podem (talvez um table?)

Build Adaptado

Por ultimo, também é válido tanto local e builds remotos, Metro pode ser configurado para adicionar e/ou remover pacotes individuais ao ultimo tarball. Digamos que você não consiga viver sem app-misc/screen, no final desse tutorial, mostraremos como obter o seu stage3 adaptado para incluí-lo.

Instalar o Metro

O método recomendado e que possui suporte é utilizar o repositório Git do Metro.

Asegure-se de que dev-vcs/git e No results (opcional; exigido para suporte EC2) sejam estalados no seu sistema:

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

Depois, clone o master git repository como a seguir:

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

Agora você terá o diretório chamado /root/metro que contem todo o código fonte do Metro.

O Metro agora está instalado. É hora de personalizá-lo para o seu sistema local.

Configuring Metro

   Note

Metro não é atualmente capaz de construir stages do Gentoo. Veja FL-901.

Daniel Robbins mantem o Metro, então ele vem pré-configurado para construir com sucesso os lançamentos do Funtoo Linux. Antes de ler mais adiante, você pode querer personalizar algumas configurações básicas como o o número de de jobs simultâneos para se encaixar as compatibilidades do seu hardware ou o diretório para utilizar arquivos stage produzidos. Isso é excelente ao editar ~/.metro a qual é o arquivo de configuração Metro's master.

Por favor, note que o path/install deve apontar para aonde o metro foi instalado. Aponte path/distfiles para aonde 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 para construir o diretório do repositório, which by default (as per the configuration file) is at /home/mirror/funtoo. The cache directory normally resides inside the temp directory -- this can be modified as desired. The cache directory can end up holding many cached .tbz2 packages, and eat up a lot of storage. You may want to place the temp directory on faster storage, for faster compile times, and place the cache directory on slower, but more plentiful storage.

   .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]

Arch and Subarch

In the following example we are creating a pentium4 stage 3 compiled for x86-32bit binary compatibility. Pentium4 is a subarch of the x86-32bit architecture. Once you have metro installed you may find a full list of each subarch in your /root/metro/subarch directory each subarch will have the file extension .spec Example:

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

First stages build (local build)

To get this all started, we need to bootstrap the process by downloading an initial seed stage3 to use for building and place it in its proper location in /home/mirror/funtoo, so that Metro can find it. We will also need to create some special "control" files in /home/mirror/funtoo, which will allow Metro to understand how it is supposed to proceed.

Step 1: Set up pentium4 repository (local build)

Assuming we're following the basic steps outlined in the previous section, and building an unstable funtoo (funtoo-current) build for the pentium4, using a generic pentium4 stage3 as a seed stage, then here the first set of steps we'd perform:

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, let's review the steps above. First, we create the directory /home/mirror/funtoo/funtoo-current/x86-32bit/pentium4, which is where Metro will expect to find unstable funtoo-current pentium4 builds -- it is configured to look here by default. Then we create a specially-named directory to house our seed x86 stage3. Again, by default, Metro expects the directory to be named this way. We enter this directory, and download our seed x86 stage3 from funtoo.org. Note that the 2010-12-24 version stamp matches. Make sure that your directory name matches the stage3 name too. Everything has been set up to match Metro's default filesystem layout.

Next, we go back to the /home/mirror/metro/funtoo-current/x86-32bit/pentium4 directory, and inside it, we create a .control directory. This directory and its subdirectories contain special files that Metro references to determine certain aspects of its behavior. The .control/version/stage3 file is used by Metro to track the most recently-built stage3 for this particular build and subarch. Metro will automatically update this file with a new version stamp after it successfully builds a new stage3. But because Metro didn't actually build this stage3, we need to set up the .control/version/stage3 file manually. This will allow Metro to find our downloaded stage3 when we set up our pentium4 build to use it as a seed. Also note that Metro will create a similar .control/version/stage1 file after it successfully builds an pentium4 funtoo-current stage1.

We also set up .control/strategy/build and .control/strategy/seed files with values of local and stage3 respectively. These files define the building strategy Metro will use when we build pentium4 funtoo-current stages. With a build strategy of local, Metro will source its seed stage from funtoo-current pentium4, the current directory. And with a seed strategy of stage3, Metro will use a stage3 as a seed, and use this seed to build a new stage1, stage2 and stage3.

Step 2: Building the pentium4 stages

Incidentally, if all you wanted to do at this point was to build a new pentium4 funtoo-current stage1/2/3 (plus openvz and vserver templates). You would begin the process by typing:

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]]