From 63879320a4d2b2852aea4b0b86bf1e017fdf6290 Mon Sep 17 00:00:00 2001 From: Mike Khiretskiy Date: Tue, 3 Mar 2015 11:00:14 +0300 Subject: [PATCH] =?UTF-8?q?=D0=94=D0=BE=D0=B1=D0=B0=D0=B2=D0=BB=D0=B5?= =?UTF-8?q?=D0=BD=D1=8B=20=D0=BA=D0=BE=D0=BC=D0=BC=D0=B5=D0=BD=D1=82=D0=B0?= =?UTF-8?q?=D1=80=D0=B8=D0=B8=20=D0=BD=D0=B0=20=D0=B0=D0=BD=D0=B3=D0=BB?= =?UTF-8?q?=D0=B8=D0=B9=D1=81=D0=BA=D0=BE=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cl-kernel | 106 +++++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 86 insertions(+), 20 deletions(-) diff --git a/cl-kernel b/cl-kernel index 0b278e4..04d8feb 100755 --- a/cl-kernel +++ b/cl-kernel @@ -26,23 +26,30 @@ DEBUG_LOG=/var/log/calculate/cl-kernel.log KVER= KERNEL_DIR=${DEFAULT_KERNEL_DIRECTORY} # создавать базовую конфигурацию ядра +# create the base kernel configuration CREATE_BASE=1 # создавать текущую конфигурацию ядра +# create the current kernel configuration CREATE_NEW=1 # собирать ядро после конфигурации +# compile the kernel once configuration is complete BUILD_KERNEL=1 # права на файл шаблона +# template file privileges CHMOD=0644 # наличие dracut в системе +# dracut present or not in the system DRACUT=$(which dracut 2>/dev/null) declare -a TAILOUT=() # прервать скрипт в случае ошибки любой из команд +# break the script execution in case of a command error set -e : >$DEBUG_LOG # вывод короткой справки +# show the short help message usage() { echo $"Usage: $0 [OPTION] @@ -54,6 +61,7 @@ ${DESCRIPTION} } # вывод полной справки +# show the long help message long_usage() { echo $"Usage: $0 [OPTION] @@ -72,6 +80,7 @@ ${DESCRIPTION} } # подготовить параметры командной строки +# prepare the commmand line parameters rearrange_params() { TEMP=$(unset POSIXLY_CORRECT; getopt \ -o "hs" \ @@ -90,6 +99,7 @@ rearrange_params() { } # выполнить параметры командной строки +# apply the command line parameters do_args() { while :; do case $1 in @@ -138,6 +148,7 @@ do_args() { } # использовать параметры из make.conf +# apply the make.conf options source_makeconf() { [[ -f /etc/make.conf ]] && source /etc/make.conf if [[ -d /etc/portage/make.conf ]] @@ -150,6 +161,7 @@ source_makeconf() { } # получить значение переменной calculate +# get the value of variable 'calculate' variable_value() { local varname=$1 @@ -157,52 +169,61 @@ variable_value() } # оставить только названия параметров + "=" +# keep parameter names only + "=" options_name() { sed -r 's/^# (CON.*) is not set.*$/\1=/' | sed -r 's/^(CON.*=).*/\1/' } # преобразовать опции в синтаксис удаления параметра +# convert the options into parameter removal syntax remove_syntax() { sed -r 's/^(.*=).*$/!\1/' } # преобразовать CONFIG_XXX=n -> # CONFIG_XXX is not set +# make the conversion # CONFIG_XXX is not set -> CONFIG_XXX=n n2not_set() { sed -r 's/(CONFIG.*)=n/# \1 is not set/' } # получить разницу в конфигурационных файлах +# get a difference of configuration files diff_config() { diff -u <(grep CONFIG_ $1 | sort | n2not_set) <(grep CONFIG_ $2 | sort | n2not_set) } # получить разницу в параметрах конфигурационных файлов +# get paramters difference of configuration files diff_config_options() { diff -u <(cat $1 | options_name | sort) <(cat $2 | options_name | sort) } # изменённые параметры +# changed parameters append_options() { diff_config $1 $2 | grep -e "^+CON" -e "^+# CON" | sed 's/^.//' | sort } # удаленные параметры +# removed parameters removed_options() { diff_config_options $1 $2 | grep -e "^-CON" | sed 's/^.//' | sort } # получить содержимое шаблона +# get the template contents diff_template_body() { append_options $1 $2 removed_options $1 $2 | remove_syntax } # вывести заголов для шаблона +# show the template headers # Args: -# категория/название пакета -# версия пакета +# category/package name +# package version diff_template_head() { local category_pn=$1 local pv=$2 @@ -210,11 +231,12 @@ diff_template_head() { } # вывести полный шаблон +# show the full template # Args: -# категория/название пакета -# версия пакета -# файл базовой конфигурации -# файл новой конфигурации +# category/package name +# package version +# base configuration file +# new configuration file create_template() { local category_pn=$1 local pv=$2 @@ -225,11 +247,12 @@ create_template() { } # получить конфигурацию ядра +# get the kernel configuration # Args: -# каталог с исходным кодом ядра -# категория/название пакета -# версия пакета -# применяемые шаблоны (локации) +# kernel sources directory +# category/package name +# package version +# used templates (locations) create_kernel_config() { local kernel_dir=$1 local category_pn=( ${2/\// } ) @@ -237,36 +260,44 @@ create_kernel_config() { local pn=${category_pn[1]} local pv=$3 # создать временную директорию для выполнения шаблонов + # create temporary directory for templates applying local tempdir=$(${MKTEMP} -d) [[ -n $4 ]] && local templates="-T $4" # получить конфигурацию ядра по умолчанию, нужной архитектуры + # get default kernel configuration for architecture local temp_config=".config_clkernel_${ARCH}" (cd ${kernel_dir};ARCH=$MARCH KCONFIG_CONFIG=${temp_config} make defconfig;mv ${temp_config} ${tempdir}/.config) &>>$DEBUG_LOG || eerror $"Failed to create the default kernel config" # выполнить шаблоны (патчи) + # apply templates (patches) /usr/sbin/cl-core-patch --march=$TEMPLATE_ARCH --pkg-name ${pn} --pkg-category ${category} --pkg-version=${pv} --pkg-slot=${pv} --pkg-path=$tempdir $templates &>>$DEBUG_LOG || eerror $"Failed to apply kernel templates" # вывести содержимое файла конфигурации ядра + # display content of kernel configuration file cat $tempdir/.config || eerror $"Kernel configuration file not found" rm -rf $tempdir &>>$DEBUG_LOG } -# проверить содержит ли каталог полный исходный код ядра +# проверить, содержит ли каталог полный исходный код ядра +# check if the directory contains the full kernel sources check_kernel_sources() { local sources_dir=$1 [[ -f ${sources_dir}/arch/x86/configs/i386_defconfig ]] } # версия исходного кода ядра +# kernel sources version sources_ver() { basename "$(readlink -f $1)" | sed 's/linux-//' || true } # текущее ядро +# current_kernel current_kernel() { sources_ver /usr/src/linux } # вывести список версий ядер с полным исходным кодом +# list all kernels with full sources available list_kernel() { local asterisk=$(echo -e "\033[1m*\033[0m") local green_asterisk=$(echo -e "\033[1;32m*\033[0m") @@ -280,13 +311,15 @@ list_kernel() { } # вывести сообщение и добавить его в список выводимых после сборки ядра сообщений +# show the message and add it to the list of messages to be displayed after compilation einfo_tail() { einfo $* TAILOUT+=( "$*" ) } # получить содержимое текущего конфига -# .config в директории исходного кода ядра +# get the content of current kernel configuration +# .config into kernel sources directory # /boot/config- # /proc/config.gz get_old_config() { @@ -318,6 +351,8 @@ _qfile() { (cd /; qfile $*) } +# проверить принадлежит ли директория только одному пакету +# check that the directory belongs to only one package check_belong() { local fn=$1 local linenum=$(_qfile -C $fn | wc -l) @@ -333,24 +368,30 @@ check_belong() { ###################### # Обработать параметры +# Process the options ###################### rearrange_params "$@" eval set -- "$TEMP" do_args "$@" ######################## -# Подготовить переменные +# Подготовить переменные +# Prepare variables ######################## # вычислить архитектуру +# detect the architecture [[ -z $MARCH ]] && MARCH=$(/usr/bin/arch) if [[ "$MARCH" == "x86" ]] || [[ "$MARCH" == "i686" ]] then # архитектура для конфигурации по умолчанию + # default configuration architecture MARCH=i386 + # templates architecture # архитектура для шаблонов TEMPLATE_ARCH=i686 # название архитектуры + # architecture name NAME_ARCH=x86 else TEMPLATE_ARCH=$MARCH @@ -358,11 +399,13 @@ else fi # подготовить имя для шаблона очистить старые временные данные +# prepare the template name; clear old temporary data TMP_TEMPLATE=/tmp/cl_kernel_${MARCH} MKTEMP="/usr/bin/mktemp ${TMP_TEMPLATE}.XXXXXX" rm -rf ${TMP_TEMPLATE}* # пропустить сборку ядра если выбранная архитектура и архитектура машины отличаются +# skip the kernel compilation if selected architecture is different from machine architecture if [[ $TEMPLATE_ARCH != $(/usr/bin/arch) ]] then OTHER_ARCH=1 @@ -370,6 +413,7 @@ then fi # вывести список доступных ядер +# list avaiable kernels if [[ $KVER == "list" ]] || [[ $KVER_OLD == "list" ]] then list_kernel $(current_kernel) @@ -377,6 +421,7 @@ then fi # получить директорию ядра по версии +# get the kernel directory by version if [[ -n $KVER ]] then KERNEL_DIR=${SRC_DIRECTORY}/linux-${KVER} @@ -386,6 +431,7 @@ then KERNEL_OLD_DIR=${SRC_DIRECTORY}/linux-${KVER_OLD} fi # проверить правильность исходников +# check the integrity of the sources for check_dir in ${KERNEL_DIR} ${KERNEL_OLD_DIR} do [[ -d ${check_dir} ]] || eerror $"Kernel directory ${check_dir} not found" @@ -393,12 +439,14 @@ do done # получить версию из директории ядра +# get the version from the kernel directory if [[ -z $KVER ]] then KVER=$(sources_ver $KERNEL_DIR) fi # проверка доступности safemode +# check if safemode is available if [[ -n $SAFEMODE ]] && ! [[ $KVER =~ -calculate ]] then eerror $"--safemode available for calculate-sources only" @@ -410,6 +458,7 @@ then fi # создать каталог в локальных шаблонах для шаблонов ядра +# create the directory for kernel templates in the local tempalte tree if ! [[ -d $LOCAL_TEMPLATES_DIR ]] then (mkdir -p $LOCAL_TEMPLATES_DIR ; @@ -418,6 +467,7 @@ then fi # если другая архитектура +# if other architecture if [[ -n $OTHER_ARCH ]] then NEW_CONFIG=${KERNEL_DIR}/.config_${TEMPLATE_ARCH} @@ -427,6 +477,7 @@ fi check_belong ${KERNEL_DIR}/Makefile # получение параметров пакета, которому принадлежат исходники +# getting the parameters for the package whose sources are being processed CATEGORY_PN=$( _qfile -C ${KERNEL_DIR}/Makefile | awk '{print $1}' ) PV=$( _qfile -Cv ${KERNEL_DIR}/Makefile | awk '{print $1}' ) PV=${PV/$CATEGORY_PN-/} @@ -439,10 +490,12 @@ then PV_OLD=${PV_OLD/${CATEGORY_PN_OLD}-/} fi -# получить версия MAJOR.MINOR для условий в шаблонах +# получить версии MAJOR.MINOR для условий в шаблонах +# get the version (MAJOR.MINOR format) for conditions in templates [[ $KVER =~ ^([[:digit:]]+\.[[:digit:]]+) ]] && PV2=${BASH_REMATCH[0]} || PV2=$PV # определение имени шаблонов для пакета +# define templates name for the package if [[ $CATEGORY_PN =~ ^.*/(.*)-sources ]] then TEMPLATE_NAME_PREFIX=10-${BASH_REMATCH[1]}- @@ -452,9 +505,10 @@ fi TEMPLATE_NAME_ARCH_PREFIX=${TEMPLATE_NAME_PREFIX}${NAME_ARCH}- TEMPLATE_NAME="${LOCAL_TEMPLATES_DIR}/${TEMPLATE_NAME_ARCH_PREFIX}${PV2}" -#################################### +######################################## # Подготовка новой конфигурации ядра -#################################### +# Preparing the new kernel configuration +######################################## CONFIG_GZ=/proc/config.gz @@ -473,15 +527,17 @@ else get_old_config fi -###################################### +######################################### # Подготовка базовой конфигурации ядра -###################################### +# Preparing the base kernel configuration +######################################### BASE_CONFIG=$( ${MKTEMP} ) ebegin $"Preparing the basic kernel configuration" if [[ -n $CREATE_BASE ]] then # будут использоваться только шаблоны оверлеев + # will be used the overlay templates only TEMPLATES=$(variable_value main.cl_template_location) create_kernel_config ${KERNEL_DIR} ${CATEGORY_PN} ${PV} ${TEMPLATES/,local,remote/} >$BASE_CONFIG else @@ -491,17 +547,20 @@ eend ########################################### # Изменение конфигурации ядра пользователем +# Manual kernel configuration ########################################### (cd $KERNEL_DIR; [[ -n ${KERNEL_OLD_DIR} || -z ${CREATE_NEW} ]] && KCONFIG_CONFIG=$(basename $NEW_CONFIG) make oldconfig;KCONFIG_CONFIG=$(basename $NEW_CONFIG) make -s menuconfig) || true ########################### # Создание шаблона +# Template creation ########################### NEW_TEMPLATE=$( ${MKTEMP} ) create_template $CATEGORY_PN $PV2 $BASE_CONFIG $NEW_CONFIG >${NEW_TEMPLATE} ################################## # Создание резервной копии шаблона +# Template backup ################################## if ls ${LOCAL_TEMPLATES_DIR}/${TEMPLATE_NAME_ARCH_PREFIX}* &>/dev/null then @@ -526,6 +585,7 @@ then fi # пропуск создания пустого шаблона +# skip the empty template if [[ $(sed 1d $NEW_TEMPLATE | wc -l) -gt 0 ]] then mv $NEW_TEMPLATE $TEMPLATE_NAME @@ -542,14 +602,16 @@ rm -f $BASE_CONFIG STARTTIME=$(date +%s) -############# +#################### # Сборка ядра -############# +# Kernel compilation +#################### if [[ -n ${BUILD_KERNEL} ]] then cd $KERNEL_DIR (source_makeconf && make clean && make $MAKEOPTS && make $MAKEOPTS modules_install && make $MAKEOPTS install) # сборка initramfs + # initramfs building if [[ -n $DRACUT ]] then grep -q "CONFIG_BLK_DEV_INITRD=y" ${NEW_CONFIG} && ${DRACUT} -fH --kver $KVER /boot/initramfs-${KVER}.img @@ -560,13 +622,16 @@ then fi fi # удалить старый ramfs если его поддержка выключена в ядре + # remove the old ramfs if its support disabled in the kernel configuration grep -q "CONFIG_BLK_DEV_INITRD=y" ${NEW_CONFIG} || rm -f /boot/initramfs-${KVER}.img || true grep -q "CONFIG_BLK_DEV_INITRD=y" ${NEW_CONFIG} || rm -f /boot/initramfs-${KVER/-calculate/-SafeMode-calculate}.img || true # выполнение шаблонов для настройки загрузки системы + # applying the templates for boot configuration cl-setup-boot # вывод времени компиляции ядра + # display kernel compilation time DELTATIME=$(( $(date +%s) - $STARTTIME )) HOUR=$(( $DELTATIME / 3600 )) DELTATIME=$(( $DELTATIME % 3600 )) @@ -583,6 +648,7 @@ then fi # вывод информационных сообщений, отображённых до сборки ядра + # display info messages, show before kernel compilation for line in "${TAILOUT[@]}" do einfo $line