Difference between pages "Project:ComRel/Developer Handbook/Developer hierarchy" and "Diskless nodes/ru"

From Gentoo Wiki
< Project:ComRel‎ | Developer Handbook(Difference between pages)
Jump to:navigation Jump to:search
m (Fix GLEP links.)
 
(Created page with "Если Вы получаете следущее сообщение, это возможно означает, что с файлом конфигурации что-то н...")
 
Line 1: Line 1:
== Introduction ==
+
<languages />
  
This section aims to explain the Gentoo development hierarchy and gives developers an insight to how Gentoo Linux development management is structured.
+
Это HOWTO поможет Вам создать и настроить бездисковые рабочие станции с Gentoo Linux.
  
== A short history of Gentoo's management structure ==
+
== Введение ==
  
The first attempt to come up with a management structure to solve problems with coordination and communication issues was made in 2003 with the structure described in [https://www.gentoo.org/glep/glep-0004.html GLEP 4]. As Gentoo grew larger over the time, some problems with the management structure were discovered and a new one was needed to solve these issues. [https://www.gentoo.org/glep/glep-0039.html GLEP 39] describes both the reasons behind this as well as the outcome of the discussion.
+
=== Об это руководстве ===
  
== Current management structure according to GLEP 39 ==
+
Это HOWTO поможет Вам настроить ''бездисковые'' рабочие станции основанные на дистрибутиве Gentoo Linux. Мы стремимся сделать это руководство настолько удобным для пользователя, насколько возможно, и также, доступным для новичка в Linux, (потому что каждый из нас был новичком в какой-то момент :) В то время как опытные пользователи могут с легкостью объединить множество доступных руководств по бездисковым станциям вместе, мы надеемся, что это руководство сможет облегчить установку для всех заинтересованных пользователей, независимо от того, гики они или нет.
  
A project is a group of developers working towards a goal (or a set of goals):
+
=== Что такое бездисковая машина? ===
  
* A project exists if it has a web page at <code><nowiki>https://wiki.gentoo.org/wiki/Project:${PROJECT_NAME}</nowiki></code> that is maintained. ("Maintained" means that the information on the page is factually correct and not out-of-date.) If the webpage isn't maintained, it is presumed dead.
+
Бездисковая машина - это компьютер без каких-либо обычных загрузочных устройств, таких как жесткие диски, дискеты, или оптические диски. Бездисковые станции загружаются по сети и требуют сервер, который обеспечит их местом для хранения данных, как это сделал бы локальный жесткий диск. С этого момента, мы будем называть сервер основным устройством - ''master'', в то время как бездисковая машина будет зависимым устройством - ''slave''. Зависимый узел требует сетевую плату с поддержкой загрузки PXE или Etherboot; проверьте поддерживаемый список по адресу [http://www.etherboot.org Etherboot.org]. Большинство современных плат поддерживает PXE, множество встроенных в материнскую плату сетевых плат также будут работать.  
* It may have one or many leads, and the leads are selected by the members of the project. This selection must occur at least once every 12 months and may occur at any time.
 
* It may have zero or more sub-projects. Sub-projects are just projects that provide some additional structure, and their web pages are in the project's space.
 
* Not everything (or everyone) needs a project.
 
* Projects need not be long-term.
 
* Projects may well conflict with other projects. That's okay.
 
* Any dev may create a new project just by creating a new page (or, more realistically, directory and page) on the wiki at [[Gentoo_Wiki:Developer_Central/Project_pages|Developer Central Project pages]] and announcing it on the gentoo-dev-announce mailing list.
 
  
Global issues will be decided by an elected Gentoo council:
+
=== Перед тем как Вы начнете ===
  
* There will be a set number of council members. (For the first election that number was set to 7 by acclamation.)
+
Вам необходимо установить Gentoo на основной узел и иметь достаточно пространства на основном узле, чтобы хранить файловые системы зависимых рабочих станций. Также, удостоверьтесь, что вы имеете один из интерфейсов подключения к интернету отдельно от подключения к локальной сети.  
* Council members will be chosen by a general election of all devs once per year.
 
* The council must hold an open meeting at least once per month.
 
* Council decisions are by majority vote of those who show up (or their proxies).
 
* If a council member (or their appointed proxy) fails to show up for two consecutive meetings, they are marked as a slacker.
 
* If a council member who has been marked a slacker misses any further meeting (or their appointed proxy doesn't show up), they lose their position and a new election is held to replace that person. The newly elected council member gets a 'reduced' term so that the yearly elections still elect a full group.
 
* Council members who have previously been booted for excessive slacking may stand for future elections, including the election for their replacement. They should, however, justify their reasons for slacking and should expect to have it pointed out if they don't do so themselves.
 
* The 'slacker' marker is reset when a member is elected.
 
* If any meeting has less than 50% attendance by council members, a new election for all places must be held within a month. The 'one year' is then reset from that point.
 
* Disciplinary actions may be appealed to the council.
 
* A proxy must not be an existing council member, and any single person may not be a proxy for more than one council member at any given meeting.
 
  
== Consequences of Gentoo's management structure ==
+
== Конфигурация основного и зависимых компьютеров ==
  
As a consequence of the new management structure, global decisions will be made by the elected council. This should give Gentoo a general direction - smaller issues affecting only a project or two should be decided inside the projects involved, probably with input from other developers. The council should be a fair representation of the developer base as every developer is able to vote, so interests should be represented in a fair way. If the council does a bad job and the developer base is unhappy with its work, the council can be voted out.
+
=== Информация о ядрах ===
  
Decisions within a project can be made by the people inside the project itself, of course coordination between the projects is necessary. The (sub-)project leads are usually responsible for doing this.
+
Ядро - это программа, которая располагается между аппаратным обеспечением и всеми остальными программами, которые загружены на Вашу машину. По существу, это сердце операционной системы, включающей в себя ядро. Когда компьютер загружается, BIOS выполняет инструкции, найденные в зарезервированном загрузочном пространстве Вашего жесткого диска. Эти инструкции обычно являются загрузчиком, который загружает ядро. После того, как ядро загружено, все процессы управляются им.  
  
Most projects have an Operational and Strategic lead, but basically it is up to the project what positions are created and how they are called - this also applies to sub-projects.
+
Чтобы найти больше информации по ядрам и их настройке, Вы можете проверить [http://www.tldp.org/HOWTO/Kernel-HOWTO.html kernel HOWTO] .  
  
Some projects appoint a contact person for communication to another project e.g. a developer within the forums project who is responsible for communication with the infrastracture project.
+
=== Конфигурация основного ядра ===
  
All in all, the current structure has no clear list of responsibilities the project leads are supposed to satisfy. They are chosen by the members of the project, the practical responsibility of a lead is "whatever the members require", and if that isn't satisfied, the members can get a new lead (if they can find somebody to take the job!).
+
Основное ядро может быть настолько большим и настроенным под Ваши нужды, насколько Вы захотите. Но в то же время, существует несколько требуемых параметров ядра, которые Вам необходимо выбрать. Перейдете в меню конфигурации ядра, введя:
  
{{Migrated|originalauthors=Seemant Kulleen, Shyam Mani, Karl Trygve Kalleberg, Mike Frysinger, Alastair Tse, Paul De Vrieze, Nicholas D. Wolfwood, Marius Mauch, Daniel Black, Wernfried Haas, Chrissy Fullam, Łukasz Damentko, Daniel Robbins, Markos Chandras, John P. Davis, Tim Yamin, Jorge Paulo, Zack Gilburd, Benny Chuang, Erwin, Jon Portnoy, Carl Anderson, Donny Davies, Peter Gavin, Dan Armak, Owen Stampflee, and Ciaran McCreesh on December 7, 2013}}
+
{{RootCmd|cd /usr/src/linux
 +
|make menuconfig}}
 +
 
 +
Вы должны получить графический интерфейс, серого и синего цвета, который предлагает безопасную альтернативу редактированию файла {{Path|/usr/src/linux/.config}} вручную. Если ядро в данный момент функционирует нормально, Вы можете сохранить текущий файл конфигурации, выйдя из графического интерфейса и введя следующую команду:
 +
 
 +
{{RootCmd|cp .config .config_working}}
 +
 
 +
Перейдите в следующие подменю и убедитесь, что перечисленные элементы меню отмечены как встроенные в ядро - built-in (а ''не как'' модули - modular). Параметры, показанные ниже, взяты из ядра версии 2.6.10. Если Вы используете другую версию, текст, или последовательность элементов меню может различаться. Просто убедитесь, что Вы, по меньшей мере, выбрали те элементы, которые показаны ниже.
 +
 
 +
{{Kernel/ru|Параметры ядра на основной системе|<pre>
 +
Code maturity level options  --->
 +
  [*] Prompt for development and/or incomplete code/drivers
 +
 
 +
Device Drivers --->
 +
  Networking options --->
 +
    <*> Packet socket
 +
    <*> Unix domain sockets
 +
    [*] TCP/IP networking
 +
    [*]  IP: multicasting
 +
    [ ] Network packet filtering (replaces ipchains)
 +
 
 +
File systems --->
 +
  Network File Systems  --->
 +
    <*> NFS server support
 +
    [*]  Provide NFSv3 server support
 +
</pre>}}
 +
 
 +
Если Вы хотите получить доступ к интернету на вашем основном узле и/или настроить безопасный межсетевой экран, убедитесь, что Вы добавили поддержку для iptables:
 +
 
 +
{{Kernel/ru|Включение поддержки iptables|<pre>
 +
  [*] Network packet filtering (replaces ipchains)
 +
  IP: Netfilter Configuration  --->
 +
    <*> Connection tracking (required for masq/NAT)
 +
    <*> IP tables support (required for filtering/masq/NAT)
 +
</pre>
 +
}}
 +
 
 +
Если Вы хотите использовать пакетную фильтрацию, Вы можете включить оставшиеся параметры в качестве модулей позже. Чтобы узнать о том, как настроить их должным образом, прочтите [http://www.gentoo.org//doc/en/security/security-handbook.xml?part=1&chap=12 Главу настольной книги по безопасности Gentoo, посвященную межсетевым экранам] .
 +
 
 +
{{Note/ru|Эти параметры конфигурации ядра должны быть добавлены только к параметрам конфигурации, характерным для системы, и не предназначены для того, чтобы полностью заменить собой настройки ядра.}}
 +
 
 +
После того, как Вы переконфигуровали ядро на основном компьютере, Вам нужно собрать его заново:
 +
 
 +
{{RootCmd|make && make modules_install
 +
|cp arch/i386/boot/bzImage /boot/bzImage-master}}
 +
 
 +
Затем добавьте запись для нового ядра в {{Path|lilo.conf}} или {{Path|grub.conf}}, в зависимости от используемого загрузчика, и сделайте новое ядро ядром, загружаемым по умолчанию. Теперь когда новый файл bzImage скопирован в загрузочный каталог, все, что Вам требуется сделать - перезагрузить систему чтобы активировать эти новые параметры.
 +
 
 +
=== Настройки зависимого ядра ===
 +
 
 +
Рекомендуется, чтобы зависимое ядро было собрано без модулей, так как их загрузка и настройка в случае удаленной загрузки ядра - сложный и ненужный процесс. Вдобавок, зависимое ядро должно быть настолько маленьким и компактным, насколько это возможно, чтобы эффективно загрузиться по сети. Мы будем компилировать зависимое ядро в том же самом месте, где было сконфигурировано основное.
 +
 
 +
Во избежание путаницы и пустой траты времени, возможно, неплохой идеей является сделать резервное копирование файла конфигурации основного ядра вводом следующих команд:
 +
 
 +
{{RootCmd|cp /usr/src/linux/.config /usr/src/linux/.config_master}}
 +
 
 +
А сейчас, нам потребуется сконфигурировать зависимое ядро тем же образом, каким мы конфигурировали основное. Если Вы хотите начать со свежего файла конфигурации, Вы всегда можете восстановить файл по умолчанию {{Path|/usr/src/linux/.config}} , введя:
 +
 
 +
{{RootCmd|cd /usr/src/linux
 +
|cp .config_master .config}}
 +
 
 +
Теперь, перейдите ко графическому интерфейсу конфигурации, с помощь ввода команды:
 +
 
 +
{{RootCmd|cd /usr/src/linux
 +
|make menuconfig}}
 +
 
 +
Вам необходимо будет удостовериться, что Вы выбрали следующие параметры как встроенные, а ''не как'' модули ядра:
 +
 
 +
{{Kernel/ru|Параметры зависимого ядра|<pre>
 +
Code maturity level options  --->
 +
  [*] Prompt for development and/or incomplete code/drivers
 +
 
 +
Device Drivers --->
 +
  [*] Networking support
 +
  Networking options --->
 +
    <*> Packet socket
 +
    <*> Unix domain sockets
 +
    [*] TCP/IP networking
 +
    [*]  IP: multicasting
 +
    [*]  IP: kernel level autoconfiguration
 +
    [*]    IP: DHCP support (NEW)
 +
 
 +
File systems --->
 +
  Network File Systems  --->
 +
    <*> file system support
 +
    [*]  Provide NFSv3 client support
 +
    [*]  Root file system on NFS
 +
</pre>
 +
}}
 +
 
 +
{{Note/ru|Альтернативой dhcp-серверу является настройка BOOTP сервера.}}
 +
 
 +
{{Important/ru|Важно, чтобы Вы добавили поддержку вашей сетевой платы в ядро (не как модуль) на узлах. Однако, использование модулей, в основном, не является проблемой для бездисковых машин.}}
 +
 
 +
Теперь необходимо собрать зависимое ядро. Вам надо действовать осторожно, чтобы не испортить какие-либо модули ядра, которые Вы собрали для основной машины:
 +
 
 +
{{RootCmd|cd /usr/src/linux
 +
|make}}
 +
 
 +
Теперь, создайте каталог на основной машине, который будет использован для хранения файлов зависимых машин и требуемых системных файлов. Мы используем каталог {{Path|/diskless}}, но Вы можете выбрать любое место, которое хотите. Сейчас, скопируйте bzImage для зависимых компьютеров в каталог {{Path|/diskless}} :
 +
 
 +
 
 +
{{Note/ru|Если Вы используете разные архитектуры, Вы можете сохранить каждый файл конфигурации в соответствующий файл {{Path|.config_arch}} . Проделайте то же самое с образами ядра: сохраните их в каталог {{Path|/diskless}} как разные файлы, названные в соответствии с архитектурой ядра - {{Path|bzImage_arch}} .}}
 +
 
 +
 
 +
{{RootCmd|mkdir /diskless
 +
|cp /usr/src/linux/arch/i386/boot/bzImage /diskless}}
 +
 
 +
=== Конфигурация предварительных файловых систем для зависимых компьютеров ===
 +
 
 +
Файловые системы для основной и зависимых систем могут быть отрегулированы и изменены в значительной степени. На данный момент мы заинтересованы только в том, как получить предварительную файловую систему с подходящими файлами конфигурации и точками монтирования. Во-первых, мы должны создать каталог внутри {{Path|/diskless}} для первой зависимой системы. Каждая зависимая система требует свою собственную корневую файловую систему, потому что разделение определенных системных файлов вызовет проблемы с разрешениями и сбои. Вы можете назвать эти каталоги так, как хотите, но я предполагаю использование IP-адресов зависимых машин, так как они уникальны и не могут быть перепутаны. Например, пусть статический IP нашей первой зависимой машины будет следующим:
 +
<code>192.168.1.21</code> :
 +
 
 +
{{RootCmd|mkdir /diskless/192.168.1.21}}
 +
 
 +
Различные файлы конфигурации в каталоге {{Path|/etc}} нуждаются в изменении для того, чтобы работать на зависимой машине. Скопируйте каталог {{Path|/etc}} основной машины на корневой каталог зависимой, введя:
 +
 
 +
{{RootCmd|cp -r /etc /diskless/192.168.1.21/etc}}
 +
 
 +
Все же, эта файловая система пока не готова, потому что ей требуются разные точки монтирования и каталоги. Чтобы их создать, введите:
 +
 
 +
{{RootCmd|mkdir /diskless/192.168.1.21/home
 +
|mkdir /diskless/192.168.1.21/dev
 +
|mkdir /diskless/192.168.1.21/proc
 +
|mkdir /diskless/192.168.1.21/tmp
 +
|mkdir /diskless/192.168.1.21/mnt
 +
|chmod a+w /diskless/192.168.1.21/tmp
 +
|mkdir /diskless/192.168.1.21/mnt/.initd
 +
|mkdir /diskless/192.168.1.21/root}}
 +
 
 +
{{RootCmd|mkdir /diskless/192.168.1.21/sys
 +
|mkdir /diskless/192.168.1.21/var
 +
|mkdir /diskless/192.168.1.21/var/empty
 +
|mkdir /diskless/192.168.1.21/var/lock
 +
|mkdir /diskless/192.168.1.21/var/log
 +
|mkdir /diskless/192.168.1.21/var/run
 +
|mkdir /diskless/192.168.1.21/var/spool
 +
|mkdir /diskless/192.168.1.21/usr
 +
|mkdir /diskless/192.168.1.21/opt
 +
}}
 +
 
 +
Большинство из этих ''файлов-заглушек'' должно быть Вам знакомо; такие заглушки как {{Path|/dev}} , {{Path|/proc}} или {{Path|/sys}} будут заполнены при запуске зависимого компьютера, остальные будут примонтированы позже. Вам также нужно изменить файл {{Path|/diskless/192.168.1.21/etc/conf.d/hostname}} , чтобы отобразить имя хоста зависимой машины. Двоичные файлы, библиотеки и другие файлы будут заполнены позже в этом руководстве, прямо перед тем, как мы попытаемся загрузить зависимый компьютер.
 +
 
 +
Даже хотя каталог {{Path|/dev}} и заполняется менеджером устройств <code>udev</code> позже, Вам требуется создать файл {{Path|console}} . Если Вы этого не сделаете, Вы получите ошибку ''unable to open initial console''.
 +
 
 +
{{RootCmd|mknod /diskless/192.168.1.21/dev/console c 5 1}}
 +
 
 +
== Конфигурация DHCP-сервера ==
 +
 
 +
=== Информация о DHCP-сервере ===
 +
 
 +
DHCP означает Dynamic Host Configuration Protocol (протокол динамической настройки узла). DHCP-сервер - это первый компьютер с которым будут соединяться зависимые машины при PXE-загрузке. Основной целью DHCP-сервера является назначение IP-адресов. DHCP-сервер может назначить адреса, основанные на MAC-адресах сети на основе ethernet. Как только зависимый компьютер получит IP-адрес, DHCP-сервер сообщит этому компьютеру где можно получить его первоначальную файловую систему и ядро.
 +
 
 +
=== Перед тем как начать ===
 +
 
 +
Перед тем как Вы начнете, проверьте что работает несколько вещей. Во-первых, проверьте соединение с сетью:
 +
 
 +
{{RootCmd|ifconfig eth0 multicast
 +
|ifconfig -a}}
 +
 
 +
Вам также необходимо убедиться, что работает устройство ''eth0''. Оно должно выглядеть следующим образом:
 +
 
 +
{{Code/ru|Устройство eth0, работающее должным образом|<pre>
 +
eth0      Link encap:Ethernet  HWaddr 00:E0:83:16:2F:D6
 +
          inet addr:192.168.1.1  Bcast:192.168.1.255  Mask:255.255.255.0
 +
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
 +
          RX packets:26460491 errors:0 dropped:0 overruns:2 frame:0
 +
          TX packets:32903198 errors:0 dropped:0 overruns:0 carrier:1
 +
          collisions:0 txqueuelen:100
 +
          RX bytes:2483502568 (2368.4 Mb)  TX bytes:1411984950 (1346.5 Mb)
 +
          Interrupt:18 Base address:0x1800
 +
</pre>
 +
}}
 +
 
 +
Важно, чтобы оно выводило ''MULTICAST''. Если это не так, Вы должны собрать ядро заново, чтобы включить поддержку multicast.
 +
 
 +
=== Установка DHCP-сервера ===
 +
 
 +
Если Ваша сеть еще не имеет установленного DHCP-сервера, Вам придется его установить:
 +
 
 +
{{Emerge|dhcp}}
 +
 
 +
Если DHCP-сервер уже присутствует в сети, Вам потребуется отредактировать файл конфигурации для корректной загрузки компьютера по сети с помощью PXE.
 +
 
 +
=== Конфигурация DHCP-сервера ===
 +
 
 +
Вам надо отредактировать только один конфигурационный файл перед запуском DHCP-сервера: {{Path|/etc/dhcp/dhcpd.conf}} . Скопируйте и отредактируйте предусмотренный файл-образец:
 +
 
 +
{{RootCmd|cp /etc/dhcp/dhcpd.conf.sample /etc/dhcp/dhcpd.conf
 +
|nano -w /etc/dhcp/dhcpd.conf}}
 +
 
 +
Основная схема этого файла задана в виде отступов и выглядит следующим образом:
 +
 
 +
{{Code/ru|Образец схемы файла dhcpd.conf|<pre>
 +
# глобальные параметры
 +
ddns-update-style none;
 +
shared-network LOCAL-NET {
 +
  # параметры shared network
 +
  subnet 192.168.1.0 netmask 255.255.255.0 {
 +
    # параметры subnet network
 +
    host slave{
 +
        # параметры, относящиеся к хосту
 +
    }
 +
    group {
 +
        # параметры, относящиеся к группе
 +
    }
 +
  }
 +
}
 +
</pre>
 +
}}
 +
 
 +
Раздел <code>shared-network</code> - необязательный и должен использоваться для назначаемых Вами IP-адресов, которые принадлежат к одной и той же топологии сети. По крайней мере, должен быть объявлен один раздел <code>subnet</code>, а необязательный раздел <code>group</code> позволяет группировать параметры между элементами. Хороший пример файла {{Path|dhcpd.conf}} выглядит так:
 +
 
 +
{{Code|Образец файла dhcpd.conf|<pre>
 +
#
 +
# Образец файла dhcpd.conf для бездисковых клиентов
 +
#
 +
 
 +
# Отключение динамической DNS
 +
ddns-update-style none;
 +
 
 +
# Предположим, достаточно одного шлюза по умолчанию
 +
option routers 192.168.1.1;
 +
 
 +
# Предоставление DNS-информации клиентам
 +
option domain-name-servers 192.168.1.1;
 +
option domain-name "mydomain.com";
 +
 
 +
# Указание используемого TFTP-сервера
 +
next-server 192.168.1.1;
 +
 
 +
# Объявление специфичного для вендора (vendor-specific) буфера параметров для клиентов PXE:
 +
# Code 1: Групповой (multicast) IP-адрес загрузочного файлового сервера
 +
# Code 2: UDP-порт, отслеживаемый клиентом для MTFTP-ответов
 +
# Code 3: UDP-порт, используемый MTFTP-серверами для прослушивания MTFTP-запросов
 +
# Code 4: Количество секунд, в течение которого клиент должен ожидать каких-либо действий,
 +
#        перед тем, как начать новую MTFTP-передачу
 +
# Code 5: Количество секунд, в течение которого клиент должен ожидать, перед перезапуском
 +
#        MTFTP-передачи
 +
 
 +
option space PXE;
 +
option PXE.mtftp-ip              code 1 = ip-address;
 +
option PXE.mtftp-cport            code 2 = unsigned integer 16;
 +
option PXE.mtftp-sport            code 3 = unsigned integer 16;
 +
option PXE.mtftp-tmout            code 4 = unsigned integer 8;
 +
option PXE.mtftp-delay            code 5 = unsigned integer 8;
 +
option PXE.discovery-control      code 6 = unsigned integer 8;
 +
option PXE.discovery-mcast-addr  code 7 = ip-address;
 +
 
 +
# Определите подсеть для размещения бездисковых рабочих станций
 +
subnet 192.168.1.0 netmask 255.255.255.0 {
 +
 
 +
  # Предоставление PXE-клиентам необходимой информации
 +
  class "pxeclient" {
 +
    match if substring(option vendor-class-identifier, 0, 9) = "PXEClient";
 +
    vendor-option-space PXE;
 +
 
 +
    # Должен быть настроен по меньшей мере один из специфичных для вендора PXE-параметров
 +
    # для того, чтобы загрузочные ПЗУ клиента - boot ROMs - располагали информацией, о том, что этот сервер PXE-совместим.
 +
    # Мы устанавливаем MCAST IP-адрес в значение 0.0.0.0 чтобы сообщить boot ROM
 +
    # что мы не можем предоставить multicast TFTP.
 +
 
 +
    option PXE.mtftp-ip 0.0.0.0;
 +
 
 +
    # Это имя файла, который должны загрузить загрузочные ПЗУ - boot ROMs.
 +
    filename "pxelinux.0";
 +
  }
 +
 
 +
  # Предоставьте необходимую информацию Etherboot-клиентам
 +
  class "etherboot" {
 +
    match if substring(option vendor-class-identifier, 0, 9) = "Etherboot";
 +
    filename "vmlinuz_arch";
 +
  }
 +
 
 +
  # Добавьте одно объявление хоста для каждой бездисковой рабочей станции
 +
  host slave21 {
 +
    hardware ethernet 00:02:A5:04:3B:66;
 +
    fixed-address 192.168.1.21;
 +
  }
 +
}
 +
</pre>
 +
}}
 +
 
 +
{{Note/ru|Ничто не запрещает использовать PXE boot и Etherboot вместе. Листинг кода, приведенный выше, просто является примером; если у Вас возникли проблемы, пожалуйста, проконсультируйтесь с документацией DHCPd.}}
 +
 
 +
С IP-адреса после <code>next-server</code> будет запрошен указанный <code>filename</code>. Этот IP-адрес должен быть IP-адресом tftp-сервера, обычно тем же самым, что и IP-адрес основной машины. <code>filename</code> является путем относительно каталога {{Path|/diskless}} (вследствие того, что параметры, относящиеся к tftp-серверу будут рассмотрены позже). Внутри раздела <code>host</code>, параметр <code>hardware ethernet</code> указывает MAC-адрес, а <code>fixed-address</code> назначает фиксированный IP адрес для этого отдельного MAC-адреса. Существует достаточно хорошая man-страница по {{Path|dhcpd.conf}} с параметрами, которые не рассмотрены в этом HOWTO. Вы можете прочитать ее, введя:
 +
 
 +
{{Cmd|man dhcpd.conf}}
 +
 
 +
=== Запуск DHCP-сервера ===
 +
 
 +
Перед тем как Вы запустите сценарий инициализации dhcp, отредактируйте файл {{Path|/etc/conf.d/dhcp}}, так, чтобы он выглядел следующим образом:
 +
 
 +
{{Code/ru|Образец /etc/conf.d/dhcp|<pre>
 +
IFACE="eth0"
 +
# Добавьте любые индивидуальные настройки по необходимости
 +
</pre>
 +
}}
 +
 
 +
Переменная <code>IFACE</code> - это устройство, на котором необходимо запустить DHCP-сервер, в нашем случае это <code>eth0</code>. Добавление большего количества аргументов к переменной <code>IFACE</code> может быть полезно в сложной топологии сети с большим количеством Ethernet-адаптеров. Чтобы запустить dhcp-сервер, введите:
 +
 
 +
{{RootCmd|/etc/init.d/dhcp start}}
 +
 
 +
Чтобы добавить dhcp-сервер к сценариям иницализации, введите:
 +
 
 +
{{RootCmd|rc-update add dhcp default}}
 +
 
 +
=== Устранение неполадок, связанных с DHCP-сервером ===
 +
 
 +
Чтобы проверить загружается ли узел сети, посмотрите сообщения в {{Path|/var/log/messages}} . Если узел загружается успешно, файл {{Path|messages}} должен содержать внизу несколько строчек, выглядящих как то:
 +
 
 +
{{Code/ru|Образец записей лог-файла, созданных dhcp|<pre>
 +
DHCPDISCOVER from 00:00:00:00:00:00 via eth0
 +
DHCPOFFER on 192.168.1.21 to 00:00:00:00:00:00 via eth0
 +
DHCPREQUEST for 192.168.1.21 from 00:00:00:00:00:00 via eth0
 +
DHCPACK on 192.168.1.21 to 00:00:00:00:00:00 via eth0
 +
</pre>
 +
}}
 +
 
 +
{{Note/ru|Этот лог-файл может также помочь в обнаружении MAC-адресов зависимых компьютеров.}}
 +
 
 +
Если Вы получаете следущее сообщение, это возможно означает, что с файлом конфигурации что-то не то, но в то же время DHCP-сервер передает данные верно.
 +
 
 +
{{Code|Sample dhpc server error|<pre>
 +
no free leases on subnet LOCAL-NET
 +
</pre>
 +
}}
 +
 
 +
Every time you change the configuration file you must restart the DHCP server. To restart the server type:
 +
 
 +
{{RootCmd|/etc/init.d/dhcpd restart}}
 +
 
 +
== Configuring the TFTP server and PXE Linux Bootloader and/or Etherboot ==
 +
 
 +
=== About the TFTP server ===
 +
 
 +
TFTP stands for Trivial File Transfer Protocol. The TFTP server is going to supply the slaves with a kernel and an initial filesystem. All of the slave kernels and filesystems will be stored on the TFTP server, so it's probably a good idea to make the master the TFTP server.
 +
 
 +
=== Installing the TFTP server ===
 +
 
 +
A highly recommended tftp server is available as the tftp-hpa package. This tftp server happens to be written by the author of SYSLINUX and it works very well with pxelinux. To install simply type:
 +
 
 +
{{Emerge|tftp-hpa}}
 +
 
 +
=== Configuring the TFTP server ===
 +
 
 +
Edit {{Path|/etc/conf.d/in.tftpd}} . You need to specify the tftproot directory with <code>INTFTPD_PATH</code> and any command line options with <code>INTFTPD_OPTS</code> . It should look something like this:
 +
 
 +
{{Code|Sample /etc/conf.d/in.tftpd|<pre>
 +
INTFTPD_PATH="/diskless"
 +
INTFTPD_OPTS="-l -v -s ${INTFTPD_PATH}"
 +
</pre>
 +
}}
 +
 
 +
The <code>-l</code> option indicates that this server listens in stand alone mode so you don't have to run inetd. The <code>-v</code> indicates that log/error messages should be verbose. The <code>-s /diskless</code> specifies the root of your tftp server.
 +
 
 +
=== Starting the the TFTP Server ===
 +
 
 +
To start the tftp server type:
 +
 
 +
{{RootCmd|/etc/init.d/in.tftpd start}}
 +
 
 +
This should start the tftp server with the options you specified in the {{Path|/etc/conf.d/in.tftpd}} . If you want this server to be automatically started at boot type:
 +
 
 +
{{RootCmd|rc-update add in.tftpd default}}
 +
 
 +
=== About PXELINUX ===
 +
 
 +
This section is not required if you are only using Etherboot. PXELINUX is the network bootloader equivalent to LILO or GRUB and will be served via TFTP. It is essentially a tiny set of instructions that tells the client where to locate its kernel and initial filesystem and allows for various kernel options.
 +
 
 +
=== Before you get started ===
 +
 
 +
You will need to get the pxelinux.0 file which comes in the SYSLINUX package by H. Peter Anvin. You can install this package by typing:
 +
 
 +
{{Emerge|syslinux}}
 +
 
 +
=== Setting up PXELINUX ===
 +
 
 +
{{Note|This isn't needed for Etherboot}}
 +
 
 +
Before you start your tftp server you need to setup pxelinux. First copy the pxelinux binary into your {{Path|/diskless}} directory:
 +
 
 +
{{RootCmd|cp /usr/share/syslinux/pxelinux.0 /diskless
 +
|mkdir /diskless/pxelinux.cfg
 +
|touch /diskless/pxelinux.cfg/default}}
 +
 
 +
This will create a default bootloader configuration file. The binary {{Path|pxelinux.0}} will look in the {{Path|pxelinux.cfg}} directory for a file whose name is the client's IP address in hexadecimal. If it does not find that file it will remove the rightmost digit from the file name and try again until it runs out of digits. Versions 2.05 and later of syslinux first perform a search for a file named after the MAC address. If no file is found, it starts the previously mentioned discovery routine. If none is found, the {{Path|default}} file is used.
 +
 
 +
{{Code|Files that PXE looks for in pxelinux.cfg/ in sequence|<pre>
 +
## (Leading 01 means Ethernet, next bytes match our slave's MAC address)
 +
01-00-40-63-c2-ca-c9
 +
 
 +
## (Assigned IP in hexadecimal)
 +
C0A80115
 +
C0A8011
 +
C0A801
 +
C0A80
 +
C0A8
 +
C0A
 +
C0
 +
C
 +
 
 +
default
 +
</pre>
 +
}}
 +
 
 +
{{Note|These are all in lowercase.}}
 +
 
 +
Let's start with the {{Path|default}} file:
 +
 
 +
{{Code|Sample pxelinux.cfg/default|<pre>
 +
DEFAULT /bzImage
 +
APPEND ip=dhcp root=/dev/nfs nfsroot=192.168.1.1:/diskless/192.168.1.21
 +
</pre>
 +
}}
 +
 
 +
The <code>DEFAULT</code> tag directs pxelinux to the kernel bzImage that we compiled earlier. The <code>APPEND</code> tag appends kernel initialisation options. Since we compiled the slave kernel with <code>NFS_ROOT_SUPPORT</code> , we will specify the nfsroot here. The first IP is the master's IP and the second IP is the directory that was created in {{Path|/diskless}} to store the slave's initial filesystem.
 +
 
 +
=== About Etherboot ===
 +
 
 +
{{Note|This isn't required if you are using PXE boot.}}
 +
 
 +
Etherboot boots network boot images from a TFTP server. As the PXE this is equivalent to LILO or GRUB. The <code>mknbi</code> utility enables you to create different images using different options.
 +
 
 +
=== Before you get started ===
 +
 
 +
You will need to get the <code>mknbi</code> (utility for making tagged kernel images useful for netbooting) package to create your Etherboot images. This tool will create a preconfigured kernel image from your original kernel. This contains the boot options as shown further down.
 +
 
 +
{{Emerge|mknbi}}
 +
 
 +
=== Setting up Etherboot ===
 +
 
 +
In this section we will create a simple etherboot image. As the dhcp server gives out the clients root-path in the "option root-path" dhcp.conf, we do not have to include this here. More details can be found in the mknbi manual.
 +
 
 +
{{Cmd|man mknbi}}
 +
 
 +
Making the boot images. This will create a ELF bootable image capable of passing dhcp and the rootpath to the kernel. Also forcing the kernel to browse the network for a dhcp server.
 +
 
 +
{{RootCmd|mkelf-linux -ip{{=}}dhcp /diskless/bzImage > /diskless/vmlinuz }}
 +
 
 +
{{Note|For the arch specific images you have to type <code>bzImage_arch</code> and <code>vmlinuz_arch</code> .}}
 +
 
 +
=== Troubleshooting the network boot process ===
 +
 
 +
There are a few things you can do to debug the network boot process. Primarily you can use a tool called <code>tcpdump</code> . To install <code>tcpdump</code> type:
 +
 
 +
{{Emerge|tcpdump}}
 +
 
 +
Now you can listen to various network traffic and make sure your client/server interactions are functioning. If something isn't working there are a few things you might want to check. First make sure that the client/server is physically connected properly and that the networking cables are not damaged. If your client/server is not receiving requests on a particular port make sure that there is no firewall interference. To listen to interaction between two computers type:
 +
 
 +
{{RootCmd|tcpdump host client_ip and server_ip}}
 +
 
 +
You can also use <code>tcpdump</code> to listen on particular port such as the tftp port by typing:
 +
 
 +
{{RootCmd|tcpdump port 69}}
 +
 
 +
A common error you might receive is: "PXE-E32: TFTP open time-out". This is probably due to firewall issues. If you are using <code>TCPwrappers</code> , you might want to check {{Path|/etc/hosts.allow}} and {{Path|etc/hosts.deny}} and make sure that they are configured properly. The client should be allowed to connect to the server.
 +
 
 +
== Configuring the NFS server ==
 +
 
 +
=== About the NFS server ===
 +
 
 +
NFS stands for Network File System. The NFS server will be used to serve directories to the slave. This part can be somewhat personalized later, but right now all we want is a preliminary slave node to boot diskless.
 +
 
 +
=== About Portmapper ===
 +
 
 +
Various client/server services do not listen on a particular port, but instead rely on RPCs (Remote Procedure Calls). When the service is initialised it listens on a random port and then registers this port with the Portmapper utility. NFS relies on RPCs and thus requires Portmapper to be running before it is started.
 +
 
 +
=== Before you start ===
 +
 
 +
The NFS Server needs kernel level support so if you don't have this you should recompile your master's kernel. To double check your master's kernel configuration type:
 +
 
 +
{{RootCmd|grep NFS /usr/src/linux/.config_master}}
 +
 
 +
You should see output that looks something like this if your kernel has been properly configured:
 +
 
 +
{{Kernel|Proper NFS specific options in the master's kernel configuration|<pre>
 +
CONFIG_PACKET=y
 +
# CONFIG_PACKET_MMAP is not set
 +
# CONFIG_NETFILTER is not set
 +
CONFIG_NFS_FS=y
 +
CONFIG_NFS_V3=y
 +
# CONFIG_NFS_V4 is not set
 +
# CONFIG_NFS_DIRECTIO is not set
 +
CONFIG_NFSD=y
 +
CONFIG_NFSD_V3=y
 +
# CONFIG_NFSD_V4 is not set
 +
# CONFIG_NFSD_TCP is not set
 +
</pre>
 +
}}
 +
 
 +
=== Installing the NFS server ===
 +
 
 +
The NFS package that can be acquired through portage by typing:
 +
 
 +
{{Emerge|nfs-utils}}
 +
 
 +
This package will emerge a portmapping utility, nfs server, and nfs client utilities and will automatically handle initialisation dependencies.
 +
 
 +
=== Configuring the NFS server ===
 +
 
 +
There are three major configuration files you will have to edit:
 +
 
 +
{{Code|Nfs configuration files|<pre>
 +
/etc/exports
 +
/diskless/192.168.1.21/etc/fstab
 +
/etc/conf.d/nfs
 +
</pre>
 +
}}
 +
 
 +
The {{Path|/etc/exports}} file specifies how, to who and what to export through NFS. The slave's fstab will be altered so that it can mount the NFS filesystems that the master is exporting.
 +
 
 +
A typical {{Path|/etc/exports}} for the master should look something like this:
 +
 
 +
{{Code|Sample master /etc/exports|<pre>
 +
# one line like this for each slave
 +
/diskless/192.168.1.21  192.168.1.21(sync,rw,no_root_squash,no_all_squash)
 +
# common to all slaves
 +
/opt  192.168.1.0/24(sync,ro,no_root_squash,no_all_squash)
 +
/usr  192.168.1.0/24(sync,ro,no_root_squash,no_all_squash)
 +
/home  192.168.1.0/24(sync,rw,no_root_squash,no_all_squash)
 +
# if you want to have a shared log
 +
/var/log  192.168.1.21(sync,rw,no_root_squash,no_all_squash)
 +
</pre>
 +
}}
 +
 
 +
The first field indicates the directory to be exported and the next field indicates to who and how. This field can be divided in two parts: who should be allowed to mount that particular directory, and what the mounting client can do to the filesystem: <code>ro</code> for read only, <code>rw</code> for read/write; <code>no_root_squash</code> and <code>no_all_squash</code> are important for diskless clients that are writing to the disk, so that they don't get "squashed" when making I/O requests. The slave's fstab file, {{Path|/diskless/192.168.1.21/etc/fstab}} , should look like this:
 +
 
 +
{{Code|Sample slave fstab|<pre>
 +
# these entries are essential
 +
master:/diskless/192.168.1.21  /        nfs    sync,hard,intr,rw,nolock,rsize=8192,wsize=8192    0 0
 +
master:/opt                    /opt      nfs    sync,hard,intr,ro,nolock,rsize=8192,wsize=8192    0 0
 +
master:/usr                    /usr      nfs    sync,hard,intr,ro,nolock,rsize=8192,wsize=8192    0 0
 +
master:/home                    /home    nfs    sync,hard,intr,rw,nolock,rsize=8192,wsize=8192    0 0
 +
none                            /proc    proc    defaults                                    0 0
 +
# useful but superfluous
 +
master:/var/log                /var/log  nfs    hard,intr,rw                                0 0
 +
</pre>
 +
}}
 +
 
 +
In this example, ''master'' is just the hostname of the master but it could easily be the IP of the master. The first field indicates the directory to be mounted and the second field indicates where. The third field describes the filesystem and should be NFS for any NFS mounted directory. The fourth field indicates various options that will be used in the mounting process (see mount(1) for info on mount options). Some people have had difficulties with soft mount points so we made them all hard, but you should look into various {{Path|/etc/fstab}} options to make your cluster more efficient.
 +
 
 +
The last file you should edit is {{Path|/etc/conf.d/nfs}} which describes a few options for nfs when it is initialised and looks like this:
 +
 
 +
{{Code|Sample master /etc/conf.d/nfs|<pre>
 +
# Config file for /etc/init.d/nfs
 +
 
 +
# Number of servers to be started up by default
 +
RPCNFSDCOUNT=8
 +
 
 +
# Options to pass to rpc.mountd
 +
RPCMOUNTDOPTS=""
 +
</pre>
 +
}}
 +
 
 +
You should change <code>RPCNFSDCOUNT</code> to the number of diskless nodes on the network.
 +
 
 +
=== Starting the NFS server ===
 +
 
 +
You should start the nfs server with its init script located in {{Path|/etc/init.d}} by typing:
 +
 
 +
{{RootCmd|/etc/init.d/nfs start}}
 +
 
 +
If you want to this script to start when the system boots simply type:
 +
 
 +
{{RootCmd|rc-update add nfs default}}
 +
 
 +
== Completing the slave filesystem ==
 +
 
 +
=== Copy the missing files ===
 +
 
 +
We will now make the slave's file system in sync with the master's and provide the necessary binaries while still preserving slave specific files.
 +
 
 +
{{RootCmd|rsync -avz /bin /diskless/192.168.1.21
 +
|rsync -avz /sbin /diskless/192.168.1.21
 +
|rsync -avz /lib /diskless/192.168.1.21}}
 +
 
 +
{{Note|The reason for rsync -avz instead of cp is to maintain symlinks and permissions.}}
 +
 
 +
=== Configure diskless networking ===
 +
 
 +
In order to prevent the networking initscript from killing the connection to your NFS server, you will need to add an option to {{Path|/etc/conf.d/net}} on your diskless client's filesystem.
 +
 
 +
{{Code|Editing /etc/conf.d/net|<pre>
 +
config_eth0=( "noop" )
 +
</pre>
 +
}}
 +
 
 +
{{Note|For more information, please read {{Path|/usr/share/doc/openrc-*/net.example.bz2}} .}}
 +
 
 +
=== Initialisation scripts ===
 +
 
 +
You need as many init scripts under {{Path|/diskless/192.168.1.21/etc/runlevels}} as you need services on your diskless nodes. It all depends on what you want your slaves to do.
 +
 
 +
{{Warning|Do not use the <code>rc-update</code> program to add or remove scripts from the slave runlevels when logged on your master. This would change your master runlevels. You need to create the links manually or log into your slave nodes using ssh or connect a screen and keyboard to your slave.}}
 +
 
 +
{{Code|Typical slave runlevels|<pre>
 +
/diskless/192.168.1.21/etc/runlevels/:
 +
total 16
 +
drwxr-xr-x    2 root    root        4096 2003-11-09 15:27 boot
 +
drwxr-xr-x    2 root    root        4096 2003-10-01 21:10 default
 +
drwxr-xr-x    2 root    root        4096 2003-03-13 19:05 nonetwork
 +
drwxr-xr-x    2 root    root        4096 2003-02-23 12:26 single
 +
 
 +
/diskless/192.168.1.21/etc/runlevels/boot:
 +
total 0
 +
lrwxrwxrwx    1 root    root          20 2003-10-18 17:28 bootmisc -> /etc/init.d/bootmisc
 +
lrwxrwxrwx    1 root    root          19 2003-10-18 17:28 checkfs -> /etc/init.d/checkfs
 +
lrwxrwxrwx    1 root    root          17 2003-10-18 17:28 clock -> /etc/init.d/clock
 +
lrwxrwxrwx    1 root    root          22 2003-10-18 17:28 domainname -> /etc/init.d/domainname
 +
lrwxrwxrwx    1 root    root          20 2003-10-18 17:28 hostname -> /etc/init.d/hostname
 +
lrwxrwxrwx    1 root    root          22 2003-10-18 17:28 localmount -> /etc/init.d/localmount
 +
lrwxrwxrwx    1 root    root          19 2003-10-18 17:28 modules -> /etc/init.d/modules
 +
lrwxrwxrwx    1 root    root          18 2003-10-18 17:28 net.lo -> /etc/init.d/net.lo
 +
lrwxrwxrwx    1 root    root          20 2003-10-18 17:28 netmount -> /etc/init.d/netmount
 +
lrwxrwxrwx    1 root    root          21 2003-10-18 17:28 rmnologin -> /etc/init.d/rmnologin
 +
lrwxrwxrwx    1 root    root          19 2003-10-18 17:28 urandom -> /etc/init.d/urandom
 +
 
 +
/diskless/192.168.1.21/etc/runlevels/default:
 +
total 0
 +
lrwxrwxrwx    1 root    root          23 2003-10-18 17:28 consolefont -> /etc/init.d/consolefont
 +
lrwxrwxrwx    1 root    root          19 2003-10-18 17:28 distccd -> /etc/init.d/distccd
 +
lrwxrwxrwx    1 root    root          19 2003-10-18 17:28 keymaps -> /etc/init.d/keymaps
 +
lrwxrwxrwx    1 root    root          17 2003-10-18 17:28 local -> /etc/init.d/local
 +
lrwxrwxrwx    1 root    root          16 2003-10-18 17:28 sshd -> /etc/init.d/sshd
 +
lrwxrwxrwx    1 root    root          21 2003-10-18 17:28 syslog-ng -> /etc/init.d/syslog-ng
 +
lrwxrwxrwx    1 root    root          17 2003-10-18 17:28 vixie-cron -> /etc/init.d/vixie-cron
 +
 
 +
/diskless/192.168.1.21/etc/runlevels/nonetwork:
 +
total 0
 +
lrwxrwxrwx    1 root    root          17 2003-10-18 17:28 local -> /etc/init.d/local
 +
 
 +
/diskless/192.168.1.21/etc/runlevels/single:
 +
total 0
 +
</pre>
 +
}}
 +
 
 +
Now is a good time to boot your slave and cross your fingers. It works? Congratulations, you are now the proud owner of (a) diskless node(s) :)
 +
 
 +
== Acknowledgements ==
 +
 
 +
We would like to thank the following authors and editors for their contributions to this guide:
 +
 
 +
 
 +
* Michael Andrews
 +
* Kristian Jerpetjoen
 +
* Sven Vermeulen
 +
* Xavier Neys

Revision as of 12:53, 28 August 2013

Это HOWTO поможет Вам создать и настроить бездисковые рабочие станции с Gentoo Linux.

Введение

Об это руководстве

Это HOWTO поможет Вам настроить бездисковые рабочие станции основанные на дистрибутиве Gentoo Linux. Мы стремимся сделать это руководство настолько удобным для пользователя, насколько возможно, и также, доступным для новичка в Linux, (потому что каждый из нас был новичком в какой-то момент :) В то время как опытные пользователи могут с легкостью объединить множество доступных руководств по бездисковым станциям вместе, мы надеемся, что это руководство сможет облегчить установку для всех заинтересованных пользователей, независимо от того, гики они или нет.

Что такое бездисковая машина?

Бездисковая машина - это компьютер без каких-либо обычных загрузочных устройств, таких как жесткие диски, дискеты, или оптические диски. Бездисковые станции загружаются по сети и требуют сервер, который обеспечит их местом для хранения данных, как это сделал бы локальный жесткий диск. С этого момента, мы будем называть сервер основным устройством - master, в то время как бездисковая машина будет зависимым устройством - slave. Зависимый узел требует сетевую плату с поддержкой загрузки PXE или Etherboot; проверьте поддерживаемый список по адресу Etherboot.org. Большинство современных плат поддерживает PXE, множество встроенных в материнскую плату сетевых плат также будут работать.

Перед тем как Вы начнете

Вам необходимо установить Gentoo на основной узел и иметь достаточно пространства на основном узле, чтобы хранить файловые системы зависимых рабочих станций. Также, удостоверьтесь, что вы имеете один из интерфейсов подключения к интернету отдельно от подключения к локальной сети.

Конфигурация основного и зависимых компьютеров

Информация о ядрах

Ядро - это программа, которая располагается между аппаратным обеспечением и всеми остальными программами, которые загружены на Вашу машину. По существу, это сердце операционной системы, включающей в себя ядро. Когда компьютер загружается, BIOS выполняет инструкции, найденные в зарезервированном загрузочном пространстве Вашего жесткого диска. Эти инструкции обычно являются загрузчиком, который загружает ядро. После того, как ядро загружено, все процессы управляются им.

Чтобы найти больше информации по ядрам и их настройке, Вы можете проверить kernel HOWTO .

Конфигурация основного ядра

Основное ядро может быть настолько большим и настроенным под Ваши нужды, насколько Вы захотите. Но в то же время, существует несколько требуемых параметров ядра, которые Вам необходимо выбрать. Перейдете в меню конфигурации ядра, введя:

root #cd /usr/src/linux
root #make menuconfig

Вы должны получить графический интерфейс, серого и синего цвета, который предлагает безопасную альтернативу редактированию файла /usr/src/linux/.config вручную. Если ядро в данный момент функционирует нормально, Вы можете сохранить текущий файл конфигурации, выйдя из графического интерфейса и введя следующую команду:

root #cp .config .config_working

Перейдите в следующие подменю и убедитесь, что перечисленные элементы меню отмечены как встроенные в ядро - built-in (а не как модули - modular). Параметры, показанные ниже, взяты из ядра версии 2.6.10. Если Вы используете другую версию, текст, или последовательность элементов меню может различаться. Просто убедитесь, что Вы, по меньшей мере, выбрали те элементы, которые показаны ниже.

Template:Kernel/ru

Если Вы хотите получить доступ к интернету на вашем основном узле и/или настроить безопасный межсетевой экран, убедитесь, что Вы добавили поддержку для iptables:

Template:Kernel/ru

Если Вы хотите использовать пакетную фильтрацию, Вы можете включить оставшиеся параметры в качестве модулей позже. Чтобы узнать о том, как настроить их должным образом, прочтите Главу настольной книги по безопасности Gentoo, посвященную межсетевым экранам .

Template:Note/ru

После того, как Вы переконфигуровали ядро на основном компьютере, Вам нужно собрать его заново:

root #make && make modules_install
root #cp arch/i386/boot/bzImage /boot/bzImage-master

Затем добавьте запись для нового ядра в lilo.conf или grub.conf, в зависимости от используемого загрузчика, и сделайте новое ядро ядром, загружаемым по умолчанию. Теперь когда новый файл bzImage скопирован в загрузочный каталог, все, что Вам требуется сделать - перезагрузить систему чтобы активировать эти новые параметры.

Настройки зависимого ядра

Рекомендуется, чтобы зависимое ядро было собрано без модулей, так как их загрузка и настройка в случае удаленной загрузки ядра - сложный и ненужный процесс. Вдобавок, зависимое ядро должно быть настолько маленьким и компактным, насколько это возможно, чтобы эффективно загрузиться по сети. Мы будем компилировать зависимое ядро в том же самом месте, где было сконфигурировано основное.

Во избежание путаницы и пустой траты времени, возможно, неплохой идеей является сделать резервное копирование файла конфигурации основного ядра вводом следующих команд:

root #cp /usr/src/linux/.config /usr/src/linux/.config_master

А сейчас, нам потребуется сконфигурировать зависимое ядро тем же образом, каким мы конфигурировали основное. Если Вы хотите начать со свежего файла конфигурации, Вы всегда можете восстановить файл по умолчанию /usr/src/linux/.config , введя:

root #cd /usr/src/linux
root #cp .config_master .config

Теперь, перейдите ко графическому интерфейсу конфигурации, с помощь ввода команды:

root #cd /usr/src/linux
root #make menuconfig

Вам необходимо будет удостовериться, что Вы выбрали следующие параметры как встроенные, а не как модули ядра:

Template:Kernel/ru

Template:Note/ru

Template:Important/ru

Теперь необходимо собрать зависимое ядро. Вам надо действовать осторожно, чтобы не испортить какие-либо модули ядра, которые Вы собрали для основной машины:

root #cd /usr/src/linux
root #make

Теперь, создайте каталог на основной машине, который будет использован для хранения файлов зависимых машин и требуемых системных файлов. Мы используем каталог /diskless, но Вы можете выбрать любое место, которое хотите. Сейчас, скопируйте bzImage для зависимых компьютеров в каталог /diskless :


Template:Note/ru


root #mkdir /diskless
root #cp /usr/src/linux/arch/i386/boot/bzImage /diskless

Конфигурация предварительных файловых систем для зависимых компьютеров

Файловые системы для основной и зависимых систем могут быть отрегулированы и изменены в значительной степени. На данный момент мы заинтересованы только в том, как получить предварительную файловую систему с подходящими файлами конфигурации и точками монтирования. Во-первых, мы должны создать каталог внутри /diskless для первой зависимой системы. Каждая зависимая система требует свою собственную корневую файловую систему, потому что разделение определенных системных файлов вызовет проблемы с разрешениями и сбои. Вы можете назвать эти каталоги так, как хотите, но я предполагаю использование IP-адресов зависимых машин, так как они уникальны и не могут быть перепутаны. Например, пусть статический IP нашей первой зависимой машины будет следующим: 192.168.1.21 :

root #mkdir /diskless/192.168.1.21

Различные файлы конфигурации в каталоге /etc нуждаются в изменении для того, чтобы работать на зависимой машине. Скопируйте каталог /etc основной машины на корневой каталог зависимой, введя:

root #cp -r /etc /diskless/192.168.1.21/etc

Все же, эта файловая система пока не готова, потому что ей требуются разные точки монтирования и каталоги. Чтобы их создать, введите:

root #mkdir /diskless/192.168.1.21/home
root #mkdir /diskless/192.168.1.21/dev
root #mkdir /diskless/192.168.1.21/proc
root #mkdir /diskless/192.168.1.21/tmp
root #mkdir /diskless/192.168.1.21/mnt
root #chmod a+w /diskless/192.168.1.21/tmp
root #mkdir /diskless/192.168.1.21/mnt/.initd
root #mkdir /diskless/192.168.1.21/root
root #mkdir /diskless/192.168.1.21/sys
root #mkdir /diskless/192.168.1.21/var
root #mkdir /diskless/192.168.1.21/var/empty
root #mkdir /diskless/192.168.1.21/var/lock
root #mkdir /diskless/192.168.1.21/var/log
root #mkdir /diskless/192.168.1.21/var/run
root #mkdir /diskless/192.168.1.21/var/spool
root #mkdir /diskless/192.168.1.21/usr
root #mkdir /diskless/192.168.1.21/opt

Большинство из этих файлов-заглушек должно быть Вам знакомо; такие заглушки как /dev , /proc или /sys будут заполнены при запуске зависимого компьютера, остальные будут примонтированы позже. Вам также нужно изменить файл /diskless/192.168.1.21/etc/conf.d/hostname , чтобы отобразить имя хоста зависимой машины. Двоичные файлы, библиотеки и другие файлы будут заполнены позже в этом руководстве, прямо перед тем, как мы попытаемся загрузить зависимый компьютер.

Даже хотя каталог /dev и заполняется менеджером устройств udev позже, Вам требуется создать файл console . Если Вы этого не сделаете, Вы получите ошибку unable to open initial console.

root #mknod /diskless/192.168.1.21/dev/console c 5 1

Конфигурация DHCP-сервера

Информация о DHCP-сервере

DHCP означает Dynamic Host Configuration Protocol (протокол динамической настройки узла). DHCP-сервер - это первый компьютер с которым будут соединяться зависимые машины при PXE-загрузке. Основной целью DHCP-сервера является назначение IP-адресов. DHCP-сервер может назначить адреса, основанные на MAC-адресах сети на основе ethernet. Как только зависимый компьютер получит IP-адрес, DHCP-сервер сообщит этому компьютеру где можно получить его первоначальную файловую систему и ядро.

Перед тем как начать

Перед тем как Вы начнете, проверьте что работает несколько вещей. Во-первых, проверьте соединение с сетью:

root #ifconfig eth0 multicast
root #ifconfig -a

Вам также необходимо убедиться, что работает устройство eth0. Оно должно выглядеть следующим образом:

Template:Code/ru

Важно, чтобы оно выводило MULTICAST. Если это не так, Вы должны собрать ядро заново, чтобы включить поддержку multicast.

Установка DHCP-сервера

Если Ваша сеть еще не имеет установленного DHCP-сервера, Вам придется его установить:

root #emerge --ask dhcp

Если DHCP-сервер уже присутствует в сети, Вам потребуется отредактировать файл конфигурации для корректной загрузки компьютера по сети с помощью PXE.

Конфигурация DHCP-сервера

Вам надо отредактировать только один конфигурационный файл перед запуском DHCP-сервера: /etc/dhcp/dhcpd.conf . Скопируйте и отредактируйте предусмотренный файл-образец:

root #cp /etc/dhcp/dhcpd.conf.sample /etc/dhcp/dhcpd.conf
root #nano -w /etc/dhcp/dhcpd.conf

Основная схема этого файла задана в виде отступов и выглядит следующим образом:

Template:Code/ru

Раздел shared-network - необязательный и должен использоваться для назначаемых Вами IP-адресов, которые принадлежат к одной и той же топологии сети. По крайней мере, должен быть объявлен один раздел subnet, а необязательный раздел group позволяет группировать параметры между элементами. Хороший пример файла dhcpd.conf выглядит так:

Template:Code

Template:Note/ru

С IP-адреса после next-server будет запрошен указанный filename. Этот IP-адрес должен быть IP-адресом tftp-сервера, обычно тем же самым, что и IP-адрес основной машины. filename является путем относительно каталога /diskless (вследствие того, что параметры, относящиеся к tftp-серверу будут рассмотрены позже). Внутри раздела host, параметр hardware ethernet указывает MAC-адрес, а fixed-address назначает фиксированный IP адрес для этого отдельного MAC-адреса. Существует достаточно хорошая man-страница по dhcpd.conf с параметрами, которые не рассмотрены в этом HOWTO. Вы можете прочитать ее, введя:

user $man dhcpd.conf

Запуск DHCP-сервера

Перед тем как Вы запустите сценарий инициализации dhcp, отредактируйте файл /etc/conf.d/dhcp, так, чтобы он выглядел следующим образом:

Template:Code/ru

Переменная IFACE - это устройство, на котором необходимо запустить DHCP-сервер, в нашем случае это eth0. Добавление большего количества аргументов к переменной IFACE может быть полезно в сложной топологии сети с большим количеством Ethernet-адаптеров. Чтобы запустить dhcp-сервер, введите:

root #/etc/init.d/dhcp start

Чтобы добавить dhcp-сервер к сценариям иницализации, введите:

root #rc-update add dhcp default

Устранение неполадок, связанных с DHCP-сервером

Чтобы проверить загружается ли узел сети, посмотрите сообщения в /var/log/messages . Если узел загружается успешно, файл messages должен содержать внизу несколько строчек, выглядящих как то:

Template:Code/ru

Template:Note/ru

Если Вы получаете следущее сообщение, это возможно означает, что с файлом конфигурации что-то не то, но в то же время DHCP-сервер передает данные верно.

Template:Code

Every time you change the configuration file you must restart the DHCP server. To restart the server type:

root #/etc/init.d/dhcpd restart

Configuring the TFTP server and PXE Linux Bootloader and/or Etherboot

About the TFTP server

TFTP stands for Trivial File Transfer Protocol. The TFTP server is going to supply the slaves with a kernel and an initial filesystem. All of the slave kernels and filesystems will be stored on the TFTP server, so it's probably a good idea to make the master the TFTP server.

Installing the TFTP server

A highly recommended tftp server is available as the tftp-hpa package. This tftp server happens to be written by the author of SYSLINUX and it works very well with pxelinux. To install simply type:

root #emerge --ask tftp-hpa

Configuring the TFTP server

Edit /etc/conf.d/in.tftpd . You need to specify the tftproot directory with INTFTPD_PATH and any command line options with INTFTPD_OPTS . It should look something like this:

Template:Code

The -l option indicates that this server listens in stand alone mode so you don't have to run inetd. The -v indicates that log/error messages should be verbose. The -s /diskless specifies the root of your tftp server.

Starting the the TFTP Server

To start the tftp server type:

root #/etc/init.d/in.tftpd start

This should start the tftp server with the options you specified in the /etc/conf.d/in.tftpd . If you want this server to be automatically started at boot type:

root #rc-update add in.tftpd default

About PXELINUX

This section is not required if you are only using Etherboot. PXELINUX is the network bootloader equivalent to LILO or GRUB and will be served via TFTP. It is essentially a tiny set of instructions that tells the client where to locate its kernel and initial filesystem and allows for various kernel options.

Before you get started

You will need to get the pxelinux.0 file which comes in the SYSLINUX package by H. Peter Anvin. You can install this package by typing:

root #emerge --ask syslinux

Setting up PXELINUX

Заметка
This isn't needed for Etherboot

Before you start your tftp server you need to setup pxelinux. First copy the pxelinux binary into your /diskless directory:

root #cp /usr/share/syslinux/pxelinux.0 /diskless
root #mkdir /diskless/pxelinux.cfg
root #touch /diskless/pxelinux.cfg/default

This will create a default bootloader configuration file. The binary pxelinux.0 will look in the pxelinux.cfg directory for a file whose name is the client's IP address in hexadecimal. If it does not find that file it will remove the rightmost digit from the file name and try again until it runs out of digits. Versions 2.05 and later of syslinux first perform a search for a file named after the MAC address. If no file is found, it starts the previously mentioned discovery routine. If none is found, the default file is used.

Template:Code

Заметка
These are all in lowercase.

Let's start with the default file:

Template:Code

The DEFAULT tag directs pxelinux to the kernel bzImage that we compiled earlier. The APPEND tag appends kernel initialisation options. Since we compiled the slave kernel with NFS_ROOT_SUPPORT , we will specify the nfsroot here. The first IP is the master's IP and the second IP is the directory that was created in /diskless to store the slave's initial filesystem.

About Etherboot

Заметка
This isn't required if you are using PXE boot.

Etherboot boots network boot images from a TFTP server. As the PXE this is equivalent to LILO or GRUB. The mknbi utility enables you to create different images using different options.

Before you get started

You will need to get the mknbi (utility for making tagged kernel images useful for netbooting) package to create your Etherboot images. This tool will create a preconfigured kernel image from your original kernel. This contains the boot options as shown further down.

root #emerge --ask mknbi

Setting up Etherboot

In this section we will create a simple etherboot image. As the dhcp server gives out the clients root-path in the "option root-path" dhcp.conf, we do not have to include this here. More details can be found in the mknbi manual.

user $man mknbi

Making the boot images. This will create a ELF bootable image capable of passing dhcp and the rootpath to the kernel. Also forcing the kernel to browse the network for a dhcp server.

root #mkelf-linux -ip=dhcp /diskless/bzImage > /diskless/vmlinuz
Заметка
For the arch specific images you have to type bzImage_arch and vmlinuz_arch .

Troubleshooting the network boot process

There are a few things you can do to debug the network boot process. Primarily you can use a tool called tcpdump . To install tcpdump type:

root #emerge --ask tcpdump

Now you can listen to various network traffic and make sure your client/server interactions are functioning. If something isn't working there are a few things you might want to check. First make sure that the client/server is physically connected properly and that the networking cables are not damaged. If your client/server is not receiving requests on a particular port make sure that there is no firewall interference. To listen to interaction between two computers type:

root #tcpdump host client_ip and server_ip

You can also use tcpdump to listen on particular port such as the tftp port by typing:

root #tcpdump port 69

A common error you might receive is: "PXE-E32: TFTP open time-out". This is probably due to firewall issues. If you are using TCPwrappers , you might want to check /etc/hosts.allow and etc/hosts.deny and make sure that they are configured properly. The client should be allowed to connect to the server.

Configuring the NFS server

About the NFS server

NFS stands for Network File System. The NFS server will be used to serve directories to the slave. This part can be somewhat personalized later, but right now all we want is a preliminary slave node to boot diskless.

About Portmapper

Various client/server services do not listen on a particular port, but instead rely on RPCs (Remote Procedure Calls). When the service is initialised it listens on a random port and then registers this port with the Portmapper utility. NFS relies on RPCs and thus requires Portmapper to be running before it is started.

Before you start

The NFS Server needs kernel level support so if you don't have this you should recompile your master's kernel. To double check your master's kernel configuration type:

root #grep NFS /usr/src/linux/.config_master

You should see output that looks something like this if your kernel has been properly configured:

Template:Kernel

Installing the NFS server

The NFS package that can be acquired through portage by typing:

root #emerge --ask nfs-utils

This package will emerge a portmapping utility, nfs server, and nfs client utilities and will automatically handle initialisation dependencies.

Configuring the NFS server

There are three major configuration files you will have to edit:

Template:Code

The /etc/exports file specifies how, to who and what to export through NFS. The slave's fstab will be altered so that it can mount the NFS filesystems that the master is exporting.

A typical /etc/exports for the master should look something like this:

Template:Code

The first field indicates the directory to be exported and the next field indicates to who and how. This field can be divided in two parts: who should be allowed to mount that particular directory, and what the mounting client can do to the filesystem: ro for read only, rw for read/write; no_root_squash and no_all_squash are important for diskless clients that are writing to the disk, so that they don't get "squashed" when making I/O requests. The slave's fstab file, /diskless/192.168.1.21/etc/fstab , should look like this:

Template:Code

In this example, master is just the hostname of the master but it could easily be the IP of the master. The first field indicates the directory to be mounted and the second field indicates where. The third field describes the filesystem and should be NFS for any NFS mounted directory. The fourth field indicates various options that will be used in the mounting process (see mount(1) for info on mount options). Some people have had difficulties with soft mount points so we made them all hard, but you should look into various /etc/fstab options to make your cluster more efficient.

The last file you should edit is /etc/conf.d/nfs which describes a few options for nfs when it is initialised and looks like this:

Template:Code

You should change RPCNFSDCOUNT to the number of diskless nodes on the network.

Starting the NFS server

You should start the nfs server with its init script located in /etc/init.d by typing:

root #/etc/init.d/nfs start

If you want to this script to start when the system boots simply type:

root #rc-update add nfs default

Completing the slave filesystem

Copy the missing files

We will now make the slave's file system in sync with the master's and provide the necessary binaries while still preserving slave specific files.

root #rsync -avz /bin /diskless/192.168.1.21
root #rsync -avz /sbin /diskless/192.168.1.21
root #rsync -avz /lib /diskless/192.168.1.21
Заметка
The reason for rsync -avz instead of cp is to maintain symlinks and permissions.

Configure diskless networking

In order to prevent the networking initscript from killing the connection to your NFS server, you will need to add an option to /etc/conf.d/net on your diskless client's filesystem.

Template:Code

Заметка
For more information, please read /usr/share/doc/openrc-*/net.example.bz2 .

Initialisation scripts

You need as many init scripts under /diskless/192.168.1.21/etc/runlevels as you need services on your diskless nodes. It all depends on what you want your slaves to do.

Предупреждение
Do not use the rc-update program to add or remove scripts from the slave runlevels when logged on your master. This would change your master runlevels. You need to create the links manually or log into your slave nodes using ssh or connect a screen and keyboard to your slave.

Template:Code

Now is a good time to boot your slave and cross your fingers. It works? Congratulations, you are now the proud owner of (a) diskless node(s) :)

Acknowledgements

We would like to thank the following authors and editors for their contributions to this guide:


  • Michael Andrews
  • Kristian Jerpetjoen
  • Sven Vermeulen
  • Xavier Neys