Compare commits

..

1 Commits

Author SHA1 Message Date
Mike Khiretskiy 1aecff46c7 Refactoring
10 years ago

6
.gitignore vendored

@ -1,6 +0,0 @@
revert_changes_to_vmachine
push_to_vmachine*
.vscode
*.pyc
*.pyo
*.bak

@ -1,5 +1,5 @@
#!/bin/bash
# Copyright 2011-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2011 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.

@ -1,5 +1,5 @@
#!/bin/bash
# Copyright 2011-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2011 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -21,8 +21,6 @@ TTYNUM=${2:-7}
DISPLAYNUM=${3:-\:0}
MAINLOOP=1
XDMCMD=/usr/share/calculate/xdm/xdm
# write pid for init.d/xdm (detect X for this xautologin)
echo $BASHPID >/var/run/bash.pid
@ -45,30 +43,6 @@ killXserver()
[[ -d /proc/$KILLXPID ]] && kill -KILL $KILLXPID &>/dev/null
}
# function for waiting X server
waitX() {
displaynum=${1#:}
usingvt="using VT number"
errorX="no screens found"
successX="evdev"
logfile=/var/log/Xorg.${displaynum}.log
for i in 0.1 0.2 0.5 1
do
sleep $i
if [[ -f $logfile ]]
then
for x in 0.5 1 2 4
do
grep -q "$errorX" $logfile && return 1
grep -q "$successX" $logfile && return 0
sleep $x
done
return 1
fi
done
return 1
}
trap killXserver SIGTERM SIGINT SIGQUIT
# rerun x session for XUSER while not shutdown and bash not receivce TERM
@ -94,54 +68,45 @@ do
# perform user profile setting up
X ${DISPLAYNUM} -auth $XAUTHORITY vt${TTYNUM} -noreset &
XPID=$!
if waitX ${DISPLAYNUM}
then
if [[ -e ${XDMCMD} ]]
then
env USER=${XUSER} ${XDMCMD} --login || break
fi
# write pam enviroment for pam_ck_connector
cat >/home/${XUSER}/.pam_environment <<EOF
env USER=${XUSER} /usr/share/calculate/xdm/xdm --login || break
# write pam enviroment for pam_ck_connector
cat >/home/${XUSER}/.pam_environment <<EOF
CKCON_DISPLAY_DEVICE=
CKCON_X11_DISPLAY_DEVICE=/dev/tty${TTYNUM}
CKCON_X11_DISPLAY=${DISPLAYNUM}
EOF
# registry user in utmp and wtmp
sessreg -a -l ${DISPLAYNUM} ${XUSER}
# run x session for user XUSER in background
su - ${XUSER} -c 'source /etc/profile
# replace xinit for startx
xinit()
{
# if file is script run it throught bash
if file $1 | grep -1 "POSIX shell script"
# registry user in utmp and wtmp
sessreg -a -l ${DISPLAYNUM} ${XUSER}
# run x session for user XUSER in background
su - ${XUSER} -c 'source /etc/profile
# replace xinit for startx
xinit()
{
# if file is script run it throught bash
if file $1 | grep -1 "POSIX shell script"
then
/bin/bash $*
else
$*
fi
}
# run script start xsession
source /usr/bin/startx' &
# wait for right work trap SIGTERM
XSESSIONPID=$!
while [[ -d /proc/$XSESSIONPID ]] &&
[[ "$(rc-status -r)" != "shutdown" ]]
do
sleep 1
done
# remove user from utmp and wtmp
sessreg -d -l ${DISPLAYNUM} ${XUSER}
# perform logout scripts for user
if [[ -n $WAITRELOGIN ]]
then
/bin/bash $*
else
$*
fi
}
# run script start xsession
source /usr/bin/startx' &
# wait for right work trap SIGTERM
XSESSIONPID=$!
while [[ -d /proc/$XSESSIONPID ]] &&
[[ "$(rc-status -r)" != "shutdown" ]]
do
sleep 1
done
# remove user from utmp and wtmp
sessreg -d -l ${DISPLAYNUM} ${XUSER}
# perform logout scripts for user
if [[ -n $WAITRELOGIN ]]
then
sleep $WAITRELOGIN
fi
if [[ -e ${XDMCMD} ]]
then
env USER=${XUSER} ${XDMCMD} --logout
fi
sleep $WAITRELOGIN
fi
env USER=${XUSER} /usr/share/calculate/xdm/xdm --logout
[[ -n $XPID ]] && kill $XPID
wait $XPID
done

@ -1,5 +1,5 @@
#!/sbin/openrc-run
# Copyright 2011-2016 Mir Calculate. http://www.calculate-linux.org
#!/sbin/runscript
# Copyright 2011 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -13,24 +13,17 @@
# See the License for the specific language governing permissions and
# limitations under the License.
CL_VIDEO_INSTALL=/usr/libexec/calculate/cl-video-install
depend() {
need localmount root fsck modules
before keymaps consolefont dbus display-manager local
before keymaps consolefont dbus xdm
use swap hostname
keyword -timeout -docker -systemd-nspawn -vserver
keyword -timeout
}
check_install_ability()
{
local pkg=$1
if [[ -d "/var/db/repos/gentoo" ]]
then
FEATURES="-getbinpkg" FETCHCOMMAND=false DISTDIR=/var/calculate/distfiles emerge -fq $pkg &>/dev/null
else
FEATURES="-getbinpkg" FETCHCOMMAND=false DISTDIR=/usr/portage/distfiles emerge -fq $pkg &>/dev/null
fi
FEATURES="-getbinpkg" FETCHCOMMAND=false DISTDIR=/usr/portage/distfiles emerge -fq $pkg &>/dev/null
}
is_already_install()
@ -46,33 +39,21 @@ install_pkg()
{
local pkg=$1
ebegin "Installing $pkg"
if [[ -d "/var/db/repos/gentoo" ]]
then
FEATURES="-getbinpkg" FETCHCOMMAND=false DISTDIR=/var/calculate/distfiles emerge $pkg &>/dev/null
else
FEATURES="-getbinpkg" FETCHCOMMAND=false DISTDIR=/usr/portage/distfiles emerge $pkg &>/dev/null
fi
FEATURES="-getbinpkg" FETCHCOMMAND=false DISTDIR=/usr/portage/distfiles emerge $pkg &>/dev/null
}
new_install_pkg()
{
local pkg=$1
local mask=$2
pkg=`echo $pkg | cut -d\/ -f2`
ebegin "Installing $pkg"
if [[ -d "/var/db/repos/gentoo" ]]
then
FETCHCOMMAND=false DISTDIR=/var/calculate/distfiles PKGDIR=/var/calculate/packages ${CL_VIDEO_INSTALL} $pkg $mask &>/dev/null
else
FETCHCOMMAND=false DISTDIR=/usr/portage/distfiles PKGDIR=/usr/portage/packages ${CL_VIDEO_INSTALL} $pkg $mask &>/dev/null
fi
FETCHCOMMAND=false DISTDIR=/usr/portage/distfiles /usr/local/sbin/cl-video-install $pkg &>/dev/null
eend $?
}
variable_value()
{
local varname=$1
/usr/libexec/calculate/cl-variable --value $varname
/usr/sbin/cl-core-variables-show --only-value $varname
}
install_video_driver()
@ -84,11 +65,8 @@ install_video_driver()
;;
nvidia)
local nvidiamask=`variable_value install.os_nvidia_mask`
if [[ -n $nvidiamask ]]
then
[[ -d /etc/portage/package.mask ]] || mkdir /etc/portage/package.mask
[[ -n $nvidiamask ]] && \
echo $nvidiamask >/etc/portage/package.mask/nvidia
fi
local drv="x11-drivers/nvidia-drivers"
;;
*)
@ -99,9 +77,9 @@ install_video_driver()
then
if ! is_already_install $drv
then
if [[ -x ${CL_VIDEO_INSTALL} ]]
if [[ -x /usr/local/sbin/cl-video-install ]]
then
new_install_pkg $drv $nvidiamask
new_install_pkg $drv
else
check_install_ability $drv && install_pkg $drv
fi
@ -124,9 +102,8 @@ create_nonroot_user() {
local nonroot_user="guest"
ebegin "Creating ${nonroot_user} user"
LANG=C useradd -p "${nonroot_pw}" \
--groups users,wheel,audio,cdrom,video,cdrw,usb,plugdev,games,lp,lpadmin,scanner,uucp \
--groups users,wheel,audio,cdrom,video,cdrw,usb,plugdev,games,lp,scanner,uucp \
${nonroot_user}
chmod 700 /home/${nonroot_user}
eend $?
fi
}
@ -149,101 +126,41 @@ setup_alsautils() {
checkpath -q -d -m 0700 -o root:root ${alsahomedir}
mkdir -p "${alsastatedir}"
local osaudio=`variable_value install.os_audio`
if [[ $osaudio == "alsa" ]]
then
local vlevel="85%"
else
local vlevel="100%"
fi
einfo "Setting up ALSA Mixer Levels"
# set output volumes to 85% - 100%
amixer -c 0 scontrols | grep -v Mic | sed -nr "/Wave|Headphone|Master|Front|LFE|Center|Side|Speaker|Surround|PCM/ s/.*'([^']+)'.*/\\1/p" | xargs -I {} amixer -c 0 -q set "{}" $vlevel unmute &>/dev/null
# reduce beep
amixer -c 0 scontrols | sed -nr "/Beep/ s/.*'([^']+)'.*/\\1/p" | xargs -I {} amixer -c 0 -q set "{}" 10% mute &>/dev/null
# mute all mics
amixer -c 0 scontrols | sed -nr "/Mic/ s/.*'([^']+)'.*/\\1/p" | xargs -I {} amixer -c 0 -q set "{}" 0% mute &>/dev/null
LANG=C alsactl -E HOME="${alsahomedir}" -I -f "${alsastatedir}/asound.state" store
fi
}
restore_filecaps() {
if [[ -f /var/lib/calculate/filecaps ]] && type filecap &>/dev/null
start() {
LANG=C /usr/sbin/cl-core --create-symlink &>/dev/null
install_video_driver
setup_alsautils
LANG=C create_nonroot_user
LANG=C /usr/sbin/cl-core --method setup_system --no-progress --usenew-conf --live on
LANG=C configure_users
LANG=C /usr/sbin/env-update
source /etc/profile
# reinit net.* services
local roottype=`variable_value main.os_root_type`
local rootdev=`variable_value main.os_root_dev`
if [[ $roottype == "livecd" ]] && [[ $rootdev == "/dev/nfs" ]]
then
while read line;
do
filecap $line
done </var/lib/calculate/filecaps
touch /* /bin/* /sbin/*
udevadm trigger --action="add" --subsystem-match=net
fi
rm -f /var/lib/calculate/filecaps
/sbin/rc-update --update
return 0
}
start() {
if rc-config list boot | grep -q -e "calculate " -e "calculate$"
stop() {
local roottype=`variable_value main.os_root_type`
if [[ $roottype == "hdd" ]] && rc-config list boot | grep -q "calculate "
then
local roottype=`variable_value main.os_root_type`
local subsystem=`variable_value main.os_subsystem`
local rootflash=`variable_value main.os_root_flash_dev`
[[ $subsystem == "lxc" ]] && restore_filecaps
if [[ $roottype != "livecd" ]] || grep "video:nvidia" /proc/cmdline &>/dev/null
then
install_video_driver
fi
setup_alsautils
LANG=C create_nonroot_user
if [[ $subsystem == "lxc" ]] || [[ $roottype == "livecd" ]]
then
LANG=C /usr/sbin/cl-core --method setup_system --no-progress --usenew-conf --live on --network on
else
LANG=C /usr/sbin/cl-core --method setup_system --no-progress --usenew-conf --live on
fi
LANG=C configure_users
[[ -n $rootflash ]] && mount -o remount,rw $rootflash
# reinit net.* services
local roottypeext=`variable_value main.os_root_type_ext`
if [[ $roottypeext == "nfs" ]]
then
touch /* /bin/* /sbin/*
fi
rc-update del calculate boot
# set en_US sort service order (make net.eth,net.br,net.wlan more preferable than NetworkManager)
LANG=en_US.utf8 /sbin/rc-update --update
udevadm control --reload
udevadm trigger --action="add" --subsystem-match=net
if [[ $subsystem != "lxc" ]] && ! [[ -f /var/calculate/server/ca/server.key ]]
then
LANG=C /usr/sbin/cl-core --bootstrap
fi
if [[ $roottype == "livecd" ]]
then
LANG=C /usr/sbin/cl-core -u guest
fi
if [[ $roottype == "hdd" ]]
then
/usr/sbin/cl-core --clear-localuser-cert
if [[ -d "/var/db/repos/gentoo" ]]
then
local distdir="/var/calculate/distfiles"
local pkgdir="/var/calculate/packages"
else
local distdir="/usr/portage/distfiles"
local pkgdir="/usr/portage/packages"
fi
local video_script="/usr/local/sbin/cl-video-install"
local cache_video="/var/cache/calculate/video_drivers"
[[ -d "${distdir}" ]] && [[ -n "`ls ${distdir}`" ]] && rm ${distdir}/*
[[ -d "${pkgdir}" ]] && [[ -n "`ls ${pkgdir}`" ]] && rm -r ${pkgdir}/*
[[ -f "${video_script}" ]] && rm -f "${video_script}"
[[ -f "${cache_video}" ]] && rm -f "${cache_video}"
fi
else
ewarn "System already configured!"
local distdir="/usr/portage/distfiles"
[[ -d "${distdir}" ]] && [[ -n "`ls ${distdir}`" ]] && rm ${distdir}/*
[[ -f /usr/local/sbin/cl-video-install ]] && rm /usr/local/sbin/cl-video-install
fi
return 0
}

@ -1,50 +0,0 @@
#!/bin/bash
PKG=$1
MASK=$2
WORLD=/var/lib/portage/world
LOG=/dev/tty12
WRITEPKG=
[[ -z "$(tail -c1 $WORLD)" ]] || echo >> $WORLD
while read category pn pv package_dir pkgname pkgmask;
do
if [[ $PKG == $pkgname ]] && [[ $MASK == $pkgmask ]]
then
if [[ $package_dir == "binary" ]]
then
binary_packages="$binary_packages =$category/$pn-$pv"
fi
fi
done </var/cache/calculate/video_drivers
if [[ -n $binary_packages ]]
then
if [[ -d "/var/db/repos/gentoo" ]]
then
ACCEPT_KEYWORDS="**" FEATURES="-getbinpkg" PKGDIR=/var/calculate/packages emerge -OK1 $binary_packages 2>&1 | cat &>>$LOG || exit 1
else
ACCEPT_KEYWORDS="**" FEATURES="-getbinpkg" PKGDIR=/usr/portage/packages emerge -OK1 $binary_packages 2>&1 | cat &>>$LOG || exit 1
fi
fi
while read category pn pv package_dir pkgname pkgmask;
do
if [[ $PKG == $pkgname ]] && [[ $MASK == $pkgmask ]]
then
if [[ $package_dir != "binary" ]]
then
cd $package_dir
ebuild=$category/$pn/$pn-${pv}.ebuild
[[ -f $ebuild ]] || git checkout $(dirname $ebuild) 2>&1 | cat &>>$LOG
if [[ -d "/var/db/repos/gentoo" ]]
then
DISTDIR=/var/calculate/distfiles ebuild $ebuild merge --skip-manifest | grep --color=never -P "^>>> [^/]" 2>&1 | cat &>>$LOG || exit 1
else
DISTDIR=/usr/portage/distfiles ebuild $ebuild merge --skip-manifest | grep --color=never -P "^>>> [^/]" 2>&1 | cat &>>$LOG || exit 1
fi
WRITEPKG="$category/$pn"
fi
fi
done </var/cache/calculate/video_drivers
[[ -n $WRITEPKG ]] && echo $WRITEPKG >>$WORLD

@ -17,13 +17,13 @@ pre {font-size:133% }
</style>
</head>
<body>
<h1 id="Quick-Installation-Guide">Quick Installation Guide<a href="#Quick-Installation-Guide" class="wiki-anchor">&para;</a></h1>
<h1 id="Installation-Guide">Installation Guide<a href="#Installation-Guide" class="wiki-anchor">&para;</a></h1>
<h2 id="Welcome-to-Calculate-Linux-">Welcome to Calculate Linux !<a href="#Welcome-to-Calculate-Linux-" class="wiki-anchor">&para;</a></h2>
<h2 id="Thank-you-for-using-Calculate-Linux">Thank you for using Calculate Linux!<a href="#Thank-you-for-using-Calculate-Linux" class="wiki-anchor">&para;</a></h2>
<p>We do our best to offer you a most convenient system for work, using the original installer, a rebranded user interface, configuration templates, Calculate Utilities and Gentoo Portage. The system is distributed as an installation image, which contains chosen software. Most of the software we have included come under the free license, thus allowing you to install, distribute and modify the source code as you feel like.</p>
<p>We do our best to offer you a most convenient system for work, using the original installer, redesigned user interface, templates, Calculate utilities and Gentoo Portage. The system is distributed as an installation image, which contains chosen software. Most of the software we have included come under the free license, thus allowing you to install, distribute and modify the source code.</p>
<p>Below is the complete list of our distributions with their abbreviations:</p>
@ -31,116 +31,134 @@ pre {font-size:133% }
<ul>
<li>CLD - Calculate Linux Desktop KDE</li>
<li>CLDC - Calculate Linux Desktop Cinnamon</li>
<li>CLDL - Calculate Linux Desktop LXQt</li>
<li>CLDM - Calculate Linux Desktop MATE</li>
<li>CLDX - Calculate Linux Desktop Xfce</li>
<li>CCM - Calculate Container Manager</li>
<li>CDS - Calculate Directory Server</li>
<li>CLS - Calculate Linux Scratch</li>
<li>CSS - Calculate Scratch Server</li>
<li>CLDG - Calculate Linux Desktop GNOME</li>
<li>CLDX - Calculate Linux Desktop XFCE</li>
<li>CLS - Calculate Linux Scratch</li>
<li>CMC - Calculate Media Center</li>
<li>CDS - Calculate Directory Server</li>
<li>CSS - Calculate Scratch Server</li>
</ul>
<p>To gain admin privileges on a system booted from a LiveCD, either <span class="bluecode" >su</span> in the graphical console emulator or hit <strong>Ctrl+Alt+F[1-8]</strong> to operate from a text-mode console. For access to your CLD, CLDC, CLDL, CLDM or CLDX desktop as <em>guest</em>, the password will be, unsurpisingly, <strong>guest</strong>.</p>
<p>To obtain administrator privileges on a system booted from a LiveCD, log in as <em>root</em> with the password <strong>root</strong>. Access to the CLD, CLDG and CLDX desktop can be obtained by the user <em>guest</em> with the password <strong>guest</strong>.</p>
<h2 id="Network-configuration">Network configuration<a href="#Network-configuration" class="wiki-anchor">&para;</a></h2>
As for any other operation performed on the Utilities Server (and this is how you setup your Internet connection with CL), you have three options for network configuration :
<ul>
<li>the graphical manager,</li>
<li>the console manager,</li>
<li>the Utilities Server, directly.</li>
</ul>
<p>Network Setup in CLD, CLDG and CLDX is performed with the Networkmanager. The program has a graphical interface with which you can configure both wired and wireless networks. When you load the program, it tries to bring up a network interface and obtain an IP address from a DHCP server. Start the program by clicking on the icon in the upper right corner of the screen.</p>
<p>Network Configuration of CLS, CDS and CSS is performed via the configuration file <code>/etc/conf.d/net</code>; help on setting up a network can be found in <code>/usr/share/doc/openrc/net.example</code>. Once you have edited the settings, restart the network interface:</p>
<pre>
/etc/init.d/net.eth0 restart
</pre>
<h2 id="Partition-management">Partition management<a href="#Partition-management" class="wiki-anchor">&para;</a></h2>
<p>Before installing, you may need to edit partitions on your hard disk. If you intend to install CLD, CLDC, CLDL, CLDM or CLDX, we recommend that you use the partition of at least 15 GB. More detailed hardware requirements can be found <a href="https://www.calculate-linux.org/main/en/hardware_requirements" target="_blank">here</a>. The swap partition will normally be twice the size of RAM. If the swap partition already exists, the system will use it. Moreover, it is wise to have a separate partition for your personal files (i.e. for the <code>/home</code> directory). See more detailed instructions on partitioning <a href="https://www.calculate-linux.org/main/en/disk_partitioning" target="_blank">here</a>.</p>
<p>Before installing, you may need to change the partitions on your hard disk. To install CLD, CLDG or CLDX, we recommend that you use the partition of at least 10 GB. More detailed hardware requirements can be found <a href="http://www.calculate-linux.org/main/en/hardware_requirements" class="external">here</a>. The swap partition (swap) will normally be twice the size of RAM. If the swap partition already exists, the system will use it. It is wise to have a separate partition for your personal files (/home). See more detailed recommendations on partitioning <a href="http://www.calculate-linux.org/main/en/disk_partitioning" class="external">here</a>.</p>
<p>CLD, CLDC, CLDL, CLDM and CLDX provide <em>Gparted</em> to edit partitions with, while CLS, CSS and CDS feature only command line utilities for the same purposes, namely <code>fdisk</code>, <code>gdisk or <code>cfdisk</code>.</p>
<p>CLD, CLDG and CLDX distro use <em>Gparted</em> to change the disk partitioning. Note that CLS and CDS contain only the command line utilities: <em>fdisk</em>,<em>gdisk</em> or <em>cfdisk</em>.</p>
<p>To list all existing partitions, open your terminal as <em>root</em> and type:<br /><pre>
<p>To view the list of all existing partitions, open the console as <em>root</em> and type:<br /><pre>
fdisk -l
</pre></p>
<p>Note: To obtain the <em>root</em> priveleges in console mode, use <code>su</code> or <code>sudo</code>.</p>
<p>Note: To obtain <em>root</em> rights in console mode, use <code>su</code> or <code>sudo</code>.</p>
<p>If you are new to Linux, it may be a while before you get used to the differences between partition names.<br />In Linux, partitions are referred to as <em>sda1, sda2, ...</em> instead of the common C:\, D:\, ...</p>
<p>If you are new to Linux, it may be a while before you get used to the differences between partition names.<br />In Linux, partitions are referred to as <code>sda1</code>, <code>sda2</code>, etc., instead of the common <code>C:\</code>, <code>D:\</code>, ...</p>
<p>You can also use the existing partitioning or create it from <em>Windows</em>. To define a given partition in Linux, remember its location and size. Usually, drive C:\ corresponds to sda1, disk D:\, to sda2.</p>
<p>You can also use the existing partitioning or repartition your hard disk from Windows. To define a given partition in Linux, remember its location and size. Typically, <code>C:\</code> would correspond to <code>sda1</code>, <code>D:\</code> to <code>sda2</code>, and so on.</p>
<p><h2 id="Installation">Installation<a href="#Installation" class="wiki-anchor">&para;</a></h2>
<p><h2 id="Installation-variants">Installation variants<a href="#Installation-variants" class="wiki-anchor">&para;</a></h2>
<p>Since Calculate Linux 10.9, we use the <code>cl-install</code> utility for installation. A graphical front-end is provided for CLD, CLDG, CLDX and CLS versions: <code>cl-console-gui</code>. To run this program, click on the icon "Calculate Linux Install" on your desktop.</p>
We provide several tools that get you install Calculate Linux. You can choose between :
<p>To install the system on the second partition of your hard disk with <code>cl-install</code>, run the following in the terminal with <em>root</em> privileges:<br /><pre>
cl-install -d /dev/sda2
</pre></p>
Here is the list of most commonly used parameters:
<ul>
<li>the GUI installer, <a href="https://www.calculate-linux.org/main/en/calculate-console-gui" target="_blank">cl-console-gui</a>,</li>
<li>the command line installer, <a href="https://www.calculate-linux.org/main/en/calculate-console" target="_blank">cl-console</a>,</li>
<li><strong>--hostname HOSTNAME</strong> - set a short or a full hostname;</li>
<li><strong>-l</strong> - the system locale. The supported languages are en_US - American English, bg_BG - Bulgarian, de_DE - German, es_ES - Spanish, fr_FR - French, it_IT - Italian, pl_PL - Polish, pt_BR - Portuguese, ru_RU - Russian, and uk_UA - Ukrainian;</li>
<li><strong>--mbr DEVICE</strong> - disk with master boot record; if set to 'off', changes will be disabled.</li>
</ul>
<p>Either a <code>squashfs</code> image (if you are installing from a LiveCD or a bootable USB media you prepared beforehand) or an ISO image can be the starting point. If the latter, it must be put in <code>/var/calculate/linux</code> or <code>/var/calculate/remote/linux</code>. In the second case, all Calculate Linux flavors are available for install, provided that the architecture you specify matches your hardware.</p>
<p>During installation, the program will extract <em>stage4</em> - that is, the image of your future system - and perform the initial configuration via templates.</p></p>
<p>All three installers are part of CL, but it is possible to use them on any Gentoo-compatible distribution. These are found in the <code>calculate</code> overlay.</p></p>
<h2 id="Installing-on-a-USB-Flash">Installing on a USB Flash<a href="#Installing-on-a-USB-Flash" class="wiki-anchor">&para;</a></h2>
<h2 id="The-first-launch">The first launch<a href="#The-first-launch" class="wiki-anchor">&para;</a></h2>
<p><em>Before you begin, we highly recommend that you make a backup of your data on a flash drive.</em></p>
<p>Once your CLD, CLDL, CLDM or CLDX system is up and running, you get two users: <em>root</em> and <em>guest</em> (if no other user accounts have been specified). Any user can get access to the graphical environment. Please note that the default password for <em>guest</em> is <strong>guest</strong>.</p>
<p>To install the system on a USB Flash, you should use the command line utility <code>cl-install</code>. Plug the flash drive to your computer. If you do not know the device name of your stick, run the following in the console with <em>root</em> privileges:<br /><pre>
fdisk -l
</pre></p>
<p>CLS as it comes out-of-box does not prompt for the password in graphical mode. To launch the window manager, run:<br /><pre>
startx
<p>If your flash drive was recognized as a <code>/dev/sdb</code> device, type the following in the console to install the system on it:<br /><pre>
cl-install -d /dev/sdb1
</pre></p>
<p>To become <em>root</em>, use the <code>su</code> command. More details on creating user accounts can be found on <a href="https://www.calculate-linux.org/main/en/create_system_users" target="_blank">this page</a>.</p>
<h2 id="The-first-launch">The first launch<a href="#The-first-launch" class="wiki-anchor">&para;</a></h2>
<p>After installing the CLD, CLDX and CLSG you get two users: <em>root</em> and <em>guest</em> (if you have not specified other user accounts). The user <em>guest</em> can get access to the graphical environment: use the username <em>guest</em> with the password <strong>guest</strong> to log in.</p>
<p>CLS, by default, does not prompt for the password in graphical mode. After installation you can login as root and launch the window manager by typing:<br /><pre>
startx
</pre></p>
<p>By default, you need to be root to log into the system remotely, via the ssh protocole. To add space for other users or to replace the root user edit the <em>AllowUsers</em> line in your <code>/etc/ssh/sshd_config</code>. We recommend that you disable remote root login.</p>
<p>To become <em>root</em>, use the <code>su</code> command. More details on creating user accounts can be found <a href="http://www.calculate-linux.org/main/en/create_system_users" class="external">here</a>.</p>
<h2 id="System-update">System update<a href="#System-update" class="wiki-anchor">&para;</a></h2>
<p>By default, you can log into the system remotely using <code>ssh</code> only as root. To add space for other users or to replace the root user edit the options AllowUsers in <code>/etc/ssh/sshd_config</code>. We recommend to deny the remote access for the <em>root</em> user.</p>
<p>Calculate Linux is a rolling-release distribution. You can update the system virtually unlimited number of times with <a href="https://wiki.calculate-linux.org/en/system_update_guide" target="_blank">cl-update</a>.</p>
<h2 id="Update">Update<a href="#Update" class="wiki-anchor">&para;</a></h2>
<p>To sync the list of packages and update all of your software, simply run:<br /><pre>
cl-update
<p>Calculate Linux is a rolling-release distribution. You can update the system virtually unlimited number of times, using the <span class="bluecode" >emerge</span> software manager. Before you update or install packages, execute the following to update the Portage tree:<br /><pre>
eix-sync
</pre></p>
<p>Or, if you want to update the list only, for the time being:<br /><pre>
cl-update --sync-only
<p>For further updates of all your software, run:<br /><pre>
emerge -uDNa world
</pre></p>
<p>After that, you can install any other applications you need with <code>emerge</code>. A quick reference can be found <a href="https://www.calculate-linux.org/main/en/add_and_remove_programs" target="_blank">here</a>. It may also be of interest to read our <a href="https://www.calculate-linux.org/main/en/system_update_guide" target="_blank">System Update Guide</a>.</p>
<p>After that, you can upgrade existing or install new versions of programs with "emerge". A quick reference can be found <a href="http://www.calculate-linux.org/main/en/add_and_remove_programs" class="external">here</a>. Read also the <a href="http://www.calculate-linux.org/main/en/system_update_guide" class="external">System Update Guide</a>.</p>
<h2 id="Help">Help<a href="#Help" class="wiki-anchor">&para;</a></h2>
<p>If you have any difficulties installing Calculate Linux, or if you want to share your impressions, feel free to visit our IRC community channel <code>#calculate</code> on FreeNode. You just have to click on the <em>Hexchat</em> icon on top of your desktop.</p>
<p>If you have any difficulties installing Calculate Linux, or if you want to share your impressions, visit the IRC channel <em>#calculate</em> (on FreeNode) of our user community. You just have to click on the Xchat icon on your desktop.</p>
<p>The project site: <a href="https://www.calculate-linux.org" target="_blank">https://www.calculate-linux.org</a><br />Our English-speaking IRC community: <a href="https://chat.calculate-linux.org/?channel=#chat" target="_blank">https://chat.calculate-linux.org</a></p>
<p>Website: <a class="external" href="http://www.calculate-linux.org">http://www.calculate-linux.org</a><br />Newsletter: <a class="external" href="http://www.calculate-linux.org/main/en/maillist">http://www.calculate-linux.org/main/en/maillist</a><br />IRC chat: <a class="external" href="http://www.calculate-linux.org/irc">http://www.calculate-linux.org/irc</a></p>
<p>You can find like-minded people on Facebook, on the <a href="https://www.facebook.com/CalculateLinux" target="_blank">Calculate Linux</a> page.</p>
<p>&nbsp;<br /><em>Enjoy!</em><br /><em>Calculate Linux Team.</em></p>
<p><em>Enjoy!</em><br /><em>Calculate Linux Team.</em></p>
</body>
</html>

@ -0,0 +1,163 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>handbook es</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
body { font:80% Verdana,Tahoma,Arial,sans-serif; }
h1, h2, h3, h4 { font-family: "Trebuchet MS",Georgia,"Times New Roman",serif; }
ul.toc { padding: 4px; margin-left: 0; }
ul.toc li { list-style-type:none; }
ul.toc li.heading2 { margin-left: 1em; }
ul.toc li.heading3 { margin-left: 2em; }
a.wiki-anchor { display: none; margin-left: 6px; text-decoration: none; }
a.wiki-anchor:hover { color: #aaa !important; text-decoration: none; }
h1:hover a.wiki-anchor, h2:hover a.wiki-anchor, h3:hover a.wiki-anchor { display: inline; color: #ddd; }
pre {font-size:133% }
</style>
</head>
<body>
<h1 id="Guía-de-instalación-rápida">Guía de instalación rápida<a href="#Guía-de-instalación-rápida" class="wiki-anchor">&para;</a></h1>
<h2 id="Bienvenidoa-a-Calculate">Bienvenido/a a Calculate!<a href="#Bienvenidoa-a-Calculate" class="wiki-anchor">&para;</a></h2>
<p>Intentabamos crear una solución de escritorio o de servidor más potente y flexible; confíamos que le gustará nuestro instalador original, una interfaz revisada que proponemos, los modelos de configuración, las utilidades Calculate con las cuales se puede administrar el sistema con facilidad, los Portages de Gentoo. Calculate Linux se distribuye en forma de una imágen de instalación y provee una hermosa lista de software preinstalado. En su mayoría, los programas que hemos incluido son cubiertos por la licencia libre; pueden ser instalados y redistribuidos libremente, y si usted es un desarrollador, le interesará que sus códigos fuentes pueden ser modificados también.</p>
Las siglas que usamos para referirnos a nuestras distribuciones son:
<ul>
<li>CLD - Calculate Linux Desktop KDE</li>
<li>CLDG - Calculate Linux Desktop GNOME</li>
<li>CLDX - Calculate Linux Desktop XFCE</li>
<li>CLS - Calculate Linux Scratch</li>
<li>CMC - Calculate Media Center</li>
<li>CDS - Calculate Directory Server</li>
<li>CSS - Calculate Scratch Server</li>
</ul>
<p>Para ponerse el administrador de un sistema Calculate arrancado desde un LiveCD, use el identificador de usuario <em>root</em> con la contraseña <strong>root</strong>. Para acceder al escritorio CLD, CLDG o CLDX, pónguese <em>guest</em> con la contraseña <strong>guest</strong>.</p>
<h2 id="Configurar-su-red">Configurar su red<a href="#Configurar-su-red" class="wiki-anchor">&para;</a></h2>
<p>CLD, CLDG y CLDX usan <em>Networkmanager</em> para configurar la red. Esta aplicación tiene una interfaz gráfica con el cual puede conectarse a través de una red alámbrica u inalámbrica. Al arranque, intentará de configurar el entorno de red automaticamente y solicitará una dirección IP del servidor DHCP. Clique encima del icono de Networkmanager en el system tray, arriba a la derecha.</p>
<p>CLS, CDS y CSS no proveen ningún instrumento grafíco para configurar la red, pués hay que editar el fichero <code>/etc/conf.d/net</code> con eso propósito. El fichero <code>/usr/share/doc/openrc-0.6.x/net.example</code> contiene una referencia sobre esto. Cuando ha modificado las opciones que importaban a usted, rearranque el entorno de red (por lo común, eth0 refiere a una red alámbrica):<br /><pre>
/etc/init.d/net.eth0 restart
</pre></p>
<h2 id="Crear-las-particiones-necesarias">Crear las particiones necesarias<a href="#Crear-las-particiones-necesarias" class="wiki-anchor">&para;</a></h2>
<p>Es posible que usted tiene necesidad de reparticionar su disco duro antes la instalación. Necesitará 10 GB minimalmente para instalar CLD, CLDG o CLDX, las cuales son las versiones más pesadas de Calculate. Por favor, lea <a href="http://www.calculate-linux.org/main/en/hardware_requirements" class="external">eso</a> si tiene preguntas sobre los requisitos de hardware. En el caso general, la partición de intercambio (swap) ha de ser el doble de la memoria RAM instalada. Si posee ya una partición swap, el sistema va a utilizarlo. Le recomendamos que reserve una partición para los datos personales (<code>/home</code>); encontrará más consejos <a href="http://www.calculate-linux.org/main/en/disk_partitioning" class="external">en la sección correspondiente</a> de eso sitio.</p>
<p>CLD sugiere utilizar <em>Partitionmanager</em>, mientras que CLDG y CLDX usan <em>Gparted</em>, pero le permiten también particionar su disco duro en el modo seudo-gráfico, con <em>cfdisk</em>. CDS, CSS y CLS, en cambio, sólo incluyen las utilidades de línea de comandos para particionar los discos: a escoger entre <em>fdisk</em> o <em>cfdisk</em>.</p>
<p>Si quiere visionar las particiones existentes, abre una Terminal y ejecute con los privilegios de <em>root</em>:<br /><pre>
fdisk -l
</pre></p>
<p>Nota: para hacerse <em>root</em>, ejecute <code>su</code> o <code>sudo</code> en la línea de comandos.</p>
<p>Los novicios en Linux necesitarán algún tiempo para familiarizarse con los nombres de los volúmenes, diferentes de los de Windows.<br />En efecto, en Linux se los suele llamar <em>sda1, sda2, ...</em> en lugar de los comunes C:\, D:\, ...</p>
<p>Sea utilice usted una partición existente, sea cree una en <em>Windows</em>. Para conocer el nombre Linux correcto de la partición escogida, memorice su orden y su tamaño. Normalmente, Linux denominará sda1 a la unidad C:\, sda2 a la unidad D:\, etc.</p>
<p><h2 id="Instalar-el-sistema">Instalar el sistema<a href="#Instalar-el-sistema" class="wiki-anchor">&para;</a></h2>
<p>Desde la versión 10.9, Calculate Linux provee su propio instalador, <code>cl-install</code> ; esto dispone de un front-end, <code>cl-install-gui</code> en CLD, CLDG, CLDX y CLS. Cárguelo clicando encima de "Instalar Calculate Linux": se repera facilmente con su símbolo de pingüino.</p>
<p>Si no obstante prefiere un instalador que funcione desde la línea de comandos (<code>cl-install</code> puro), y si asumimos, por ejemplo, que desea instalar su nuevo sistema en la secunda partición del disco duro, pónguese <em>root</em> y ejecute:<br /><pre>
cl-install -d /dev/sda2
</pre></p>
Las optiones más útiles de <code>cl-install</code> son :
<ul>
<li><strong>--hostname HOSTNAME</strong> - indica el nombre abreviado o completo del host;</li>
<li><strong>-l</strong> - indica el locale de su sistema. Los locales soportados son: en_US (inglés americano), bg_BG (búlgaro), de_DE (alemán), es_ES (español), fr_FR (francés), it_IT (italiano), pl_PL (polonés), pt_BR (portugués), ru_RU (ruso) y uk_UA (ucraniano);</li>
<li><strong>--mbr DEVICE</strong> - indica el disco con el MBR ; si el valor afectado es 'off', alguna modificación será desechada.</li>
</ul>
<p>En el transcurso de la instalación, el programa va al extraer los ficheros de <em>stage4</em> - eso es, el imágen de su futuro sistema - y, después, a preconfigurarlo con los modelos que van con la distribución.</p></p>
<h3 id="Instalar-en-una-memoria-USB">Instalar en una memoria USB<a href="#Instalar-en-una-memoria-USB" class="wiki-anchor">&para;</a></h3>
<p><em>¡Antes que empieza, no olvide hacer una copia de seguridad de los datos que conserva en la memoria!</em></p>
<p>Si planea instalar Calculate Linux en una memoria USB, debe cargar <code>cl-install</code> desde una Terminal. Primero hay que colocar la memoria en la máquina. Entonces, para conocer su nombre de periférico, ejecute como <em>root</em>:<br /><pre>
fdisk -l
</pre></p>
<p>En el siguiente exemplo, trataremos de instalar Calculate Linux en una unidad flash reconocida como un periférico <code>/dev/sdb</code>:<br /><pre>
cl-install -d /dev/sdb1
</pre></p>
<h2 id="Arrancar-el-sistema-por-la-primera-vez">Arrancar el sistema por la primera vez<a href="#Arrancar-el-sistema-por-la-primera-vez" class="wiki-anchor">&para;</a></h2>
<p>Si instala CLD, CLDG o CLDX sin señalar al sistema que usted desea otros usuarios, solas dos cuentas, <em>root</em> y <em>guest</em>, serán creadas. Cualquier usuario, salvo <em>root</em>, podrá acceder al entorno grafíco. La contraseña del usuario anónimo <em>guest</em> es por defecto <strong>guest</strong>.</p>
<p>En una CLS recién instalada, no hay invitación gráfica. Para lanzar el gestor de ventanas, ejecute:<br /><pre>
startx
</pre></p>
<p>Para obtener los privilegios de <em>root</em>, le recordamos que lo único que necesita hacer es cargar <code>su</code> desde la línea de comandos. Explicamos <a href="http://www.calculate-linux.org/main/en/create_system_users" class="external">aquí</a> cómo se añaden unos usuarios más.</p>
<p>Por defecto, no puede acceder al sistema remoto (mediante el protocolo ssh) sin privilegios de root. Probablemente hará falta crear otras cuentas de usuario, poniéndolas en el parámetro <em>AllowUsers</em>, el cual se utuliza en el fichero de configuración <code>/etc/ssh/sshd_config</code>. Además le aconsejamos que denegue el acceso remoto al usuario <em>root</em>.</p>
<h2 id="Actualizar-el-software">Actualizar el software<a href="#Actualizar-el-software" class="wiki-anchor">&para;</a></h2>
<p>Calculate Linux es una distribución rolling release; eso es, usted puede actualizarla en alguno momento, quando se apetece, si quiere tener lo último de lo último. <a href="http://www.calculate-linux.org/main/en/emerge" class="external">emerge</a> se ocupa de todo. Antes de instalar algo, actualize el árbol Portage con el siguiente comando:<br /><pre>
eix-sync
</pre></p>
<p>Para actualizar todo el software que posee en su sistema, ejecute:<br /><pre>
emerge -uDNa world
</pre></p>
<p>Después también podrá actualizar los programas u instalar unas nuevas aplicaciones con el gestor de paquetes <em>emerge</em>. Encontrará una referencia rápida sobre esto <a href="http://www.calculate-linux.org/main/en/add_and_remove_programs" class="external">por aquí</a>. Lea también nuestra <a href="http://www.calculate-linux.org/main/en/system_update_guide" class="external">Guía de actualización</a>.</p>
<h2 id="Ayuda">Ayuda<a href="#Ayuda" class="wiki-anchor">&para;</a></h2>
<p>Si tiene dificultad para instalar Calculate Linux, o si le gustaría a usted compartir sus impresiones, visitenos en nuestros canales <em>IRC</em>: le basta a usted clicar encima del icono de <em>Xchat</em> sobre su escritorio (arriba a la izquierda).</p>
<h2 id="Recursos-útiles">Recursos útiles<a href="#Recursos-útiles" class="wiki-anchor">&para;</a></h2>
<p>El sitio del proyecto Calculate (EN): <a class="external" href="http://www.calculate-linux.org">http://www.calculate-linux.org</a><br />Nuestra lista de correo (EN): <a class="external" href="http://www.calculate-linux.org/main/en/maillist">http://www.calculate-linux.org/main/en/maillist</a><br />Nuestros canales IRC: <code>#calculate-es</code> (en español) o <code>#calculate</code> (en inglés) sobre <em>irc.freenode.net</em></p>
<p><em>¡Disfrutese!<br />Los desarrolladores de Calculate Linux</em></p>
</body>
</html>

@ -0,0 +1,165 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>handbook fr</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style>
body { font:80% Verdana,Tahoma,Arial,sans-serif; }
h1, h2, h3, h4 { font-family: "Trebuchet MS",Georgia,"Times New Roman",serif; }
ul.toc { padding: 4px; margin-left: 0; }
ul.toc li { list-style-type:none; }
ul.toc li.heading2 { margin-left: 1em; }
ul.toc li.heading3 { margin-left: 2em; }
a.wiki-anchor { display: none; margin-left: 6px; text-decoration: none; }
a.wiki-anchor:hover { color: #aaa !important; text-decoration: none; }
h1:hover a.wiki-anchor, h2:hover a.wiki-anchor, h3:hover a.wiki-anchor { display: inline; color: #ddd; }
pre {font-size:133% }
</style>
</head>
<body>
<h1 id="Calculate-Linux-Guide-dinstallation-rapide">Calculate Linux : Guide d'installation rapide<a href="#Calculate-Linux-Guide-dinstallation-rapide" class="wiki-anchor">&para;</a></h1>
<h2 id="Bienvenue-sur-Calculate-">Bienvenue sur Calculate !<a href="#Bienvenue-sur-Calculate-" class="wiki-anchor">&para;</a></h2>
<p>Nous souhaitions vous proposer une solution bureau ou serveur performante, mais conviviale au possible ; nous espérons l'avoir fait, avec notre installateur original, une interface entièrement refaite, les modèles de configuration, les utilitaires Calculate et les Portages Gentoo. Calculate Linux est distribuée sous forme d'un LiveCD d'installation qui inclut des applications de choix. La plupart des logiciels sont mis à disposition sous la licence libre et peuvent, de ce fait, être distribués et installés sans aucune restriction ; leurs codes sources sont librement modifiables.</p>
<p>Voici les acronymes que nous utilisons pour désigner les différentes versions de Calculate :</p>
<ul>
<li>CLD - Calculate Linux Desktop KDE</li>
<li>CLDG - Calculate Linux Desktop GNOME</li>
<li>CLDX - Calculate Linux Desktop XFCE</li>
<li>CLS - Calculate Linux Scratch</li>
<li>CMC - Calculate Media Center</li>
<li>CDS - Calculate Directory Server</li>
<li>CSS - Calculate Scratch Server</li>
</ul>
<p>Pour avoir les droits d'administrateur en mode live, identifiez-vous comme <em>root</em> avec le mot de passe <strong>root</strong>. Vous pouvez accéder à votre bureau CLD, CLDG ou CLDX en tant qu'utilisateur <em>guest</em> dont le mot de passe est <strong>guest</strong>.</p>
<h2 id="Configurer-votre-connexion-réseau">Configurer votre connexion réseau<a href="#Configurer-votre-connexion-réseau" class="wiki-anchor">&para;</a></h2>
<p>Si vous avez opté pour CLD, CLDG ou CLDX, <em>Networkmanager</em> vous aide à configurer votre connection Internet. Ce gestionnaire de réseau fournit une interface graphique qui permet de se connecter en toute facilité, qu'il s'agisse d'un réseau filaire ou sans fil. Au démarrage, il essayera de configurer votre réseau et d'obtenir une adresse IP automatiquement, par un serveur DHCP. Pour ouvrir <em>Networkmanager</em>, cliquez sur son icône dans la zone de notification (en haut à droite).</p>
<p>Quant à CLS, CDS ou encore CSS, il vous faudra éditer le fichier de configuration <code>/etc/conf.d/net</code> pour pouvoir vous connecter. Pour plus d'informations, voir <code>/usr/share/doc/openrc-0.6.x/net.example</code>. Après avoir modifié les réglages réseau, redémarrez l'interface (dans le cas général, ce sera eth0 pour un réseau filaire) :<br /><pre>
/etc/init.d/net.eth0 restart
</pre></p>
<h2 id="Partitionner-votre-disque">Partitionner votre disque<a href="#Partitionner-votre-disque" class="wiki-anchor">&para;</a></h2>
<p>Avant d'installer Calculate Linux, vous devrez probablement modifier le partitionnement de votre disque dur. L'installation de CLD, CLDG et CLDX, les versions les plus " lourdes " de Calculate, nécessitera une partition de 10 Go minimum. Les prérequis matériel sont détaillés <a href="http://www.calculate-linux.org/main/en/hardware_requirements" class="external">sur cette page</a>. Normalement, la taille de la mémoire virtuelle (ou swap) doit être égale à deux fois la taille de la mémoire vive. Si une partition swap existe déjà, le système l'utilisera. Nous conseillons de stocker vos fichiers personnels, alias le répertoire <code>/home</code>, sur une partition à part. Pour plus de conseils sur le partionnement, lisez <a href="http://www.calculate-linux.org/main/en/disk_partitioning" class="external">ceci</a>.</p>
<p>CLD est fournie avec l'application <em>Partitionmanager</em>, pour gérer les partitions, alors que CLDG et CLDX sont censées utiliser <em>Gparted</em> à ces mêmes fins. Vous pouvez également partitionner votre disque dur en mode pseudo-graphique, avec <em>cfdisk</em>. Les versions CDS, CSS et CLS, en revanche, n'ont que des outils console à vous proposer, à savoir <em>fdisk</em> ou <em>cfdisk</em>.</p>
<p>Pour afficher le plan de partitionnement actuel, lancez le Terminal avec les privilèges <em>root</em> et tapez :<br /><pre>
fdisk -l
</pre></p>
<p>Note : pour devenir <em>root</em> (provisoirement), exécutez <code>su</code> ou <code>sudo</code> en console.</p>
<p>Si vous êtes novice à Linux, sachez que les partitions apparaîtront dans le système sous des noms différents de celles de Windows.<br />En effet, Linux nomme les partitions <em>sda1, sda2, ...</em>, et non pas C:\, D:\, ..., dénominations auxquelles les usagers de Windows sont habitués.</p>
<p>Vous avez deux options : soit vous utilisez une partition qui existe déjà sur votre disque dur, soit vous (re)partitionnez le disque sous <em>Windows</em>. Pour ne pas vous tromper sur le nom Linux de la partition choisie, mémoriser l'ordre dans lequel elle apparaît et sa taille. Généralement, sda1 correspondra au disque C:\, sda2, au disque D:\, etc.</p>
<p><h2 id="Installation">Installation<a href="#Installation" class="wiki-anchor">&para;</a></h2>
<p>A partir de la version 10.9, Calculate Linuxwe a son propre installateur, <code>cl-install</code> ; ce dernier dispose d'un frontal graphique, <code>cl-install-gui</code> dans CLD, CLDG, CLDX et CLS. Pour le lancer, cliquez sur le raccourci "Installer Calculate Linux", facilement repérable sur le bureau.</p>
<p>Si vous préférez quand même l'installateur console (<code>cl-install</code>, sans fioritures), et que vous voulez installer le nouveau système en réservant à celui-ci, disons, la deuxième partition de votre disque dur, exécutez sous <em>root</em> :<br /><pre>
cl-install -d /dev/sda2
</pre></p>
Les options les plus utiles de cette commande sont :
<ul>
<li><strong>--hostname HOSTNAME</strong> - indiquer le nom abrégé ou complet de l'hôte ;</li>
<li><strong>-l</strong> - définir la locale système. Les locales supportées sont : en_US (anglais américain), bg_BG (bulgare), de_DE (allemand), es_ES (espagnol), fr_FR (français), it_IT (italien), pl_PL (polonais), pt_BR (portugais), ru_RU (russe) et uk_UA (ukrainien) ;</li>
<li><strong>--mbr DEVICE</strong> - indiquer le disque avec le MBR ; si la valeur affectée est 'off', toute modification sera rejetée.</li>
</ul>
<p>Lors de l'installation, le programme va extraire les données de <em>stage4</em> - c'est-à-dire, l'image de votre futur système - et les préconfigurer avec les modèles fournis.</p></p>
<h3 id="Installer-sur-une-clé-USB">Installer sur une clé USB<a href="#Installer-sur-une-clé-USB" class="wiki-anchor">&para;</a></h3>
<p><em>Avant de procéder à l'installation, il est vivement conseillé de faire une copie de réserve de toutes vos données (en les sauvegardant sur une autre clé USB, par exemple) !</em></p>
<p>L'installation du système sur un support USB se fait avec l'utilitaire <code>cl-install</code>, qui se lance à partir de la console. Naturellement, il vous faudra d'abord brancher la clé ; ensuite, pour connaître son nom de périphérique, exécutez sous <em>root</em> dans votre Terminal:<br /><pre>
fdisk -l
</pre></p>
<p>Si, par exemple, votre clé USB a été identifiée comme un périphérique <code>/dev/sdb</code>, vous y installerez Calculate Linux en tapant :<br /><pre>
cl-install -d /dev/sdb1
</pre></p>
<h2 id="Démarrer-pour-la-première-fois">Démarrer pour la première fois<a href="#Démarrer-pour-la-première-fois" class="wiki-anchor">&para;</a></h2>
<p>Une fois votre système CLD, CLDG ou CLDX installé, deux comptes utilisateur seront créés, en plus de vos comptes personnalisés si vous en avez ajouté au moins un : <em>root</em> et <em>guest</em>. Tout utilisateur sauf <em>root</em> peut accéder à la session graphique. Par défaut, le mot de passe de l'utilisateur anonyme <em>guest</em> est <strong>guest</strong>.</p>
<p>Notez que, juste après l'installation, CLS ne fournit pas d' invitation graphique du mot de passe. Pour lancer le gestionnaire de fenêtres, tapez<br /><pre>
startx
</pre></p>
<p>Afin de pouvoir travailler avec les privilèges de <em>root</em>, utilisez la commande <code>su</code>. Si vous souhaitez créer un nouveau compte utilisateur, veuillez lire <a href="http://www.calculate-linux.org/main/en/create_system_users" class="external">la section correspondante de la documentation</a>.</p>
<p>Vous ne pouvez vous connecter à distance (via le protocole ssh) que doté de privilèges <em>root</em>. Il est possible d'éditer le fichier <code>/etc/ssh/sshd_config</code> en ajoutant des comptes utilisateur à la valeur du paramètre <em>AllowUsers</em> ; nous vous recommandons d'ailleurs d'interdire à l'utilisateur <em>root</em> d'accéder au système à distance.</p>
<h2 id="Mettre-à-jour-votre-système">Mettre à jour votre système<a href="#Mettre-à-jour-votre-système" class="wiki-anchor">&para;</a></h2>
<p>Calculate Linux propose la mise à jour en continu. Vous pourrez donc la faire à tout moment, tant que vous voulez : <a href="http://www.calculate-linux.org/main/en/emerge" class="external">emerge</a> s'en charge. Commencez par mettre à jour l'arbre Portage :<br /><pre>
eix-sync
</pre></p>
<p>Pour la mise à jour de toutes vos applications, exécutez :<br /><pre>
emerge -uDNa world
</pre></p>
<p>Par la suite, vous pourrez installer ou désinstaller des logiciels avec le gestionnaire de paquets <em>emerge</em>. Pour vous renseigner rapidement sur la gestion des logiciels, référez-vous <a href="http://www.calculate-linux.org/main/en/add_and_remove_programs" class="external">ici</a>. Pensez également à consulter notre <a href="http://www.calculate-linux.org/main/en/system_update_guide" class="external">Guide de mise à jour</a>.</p>
<h2 id="Dépannage">Dépannage<a href="#Dépannage" class="wiki-anchor">&para;</a></h2>
<p>Si vous rencontrez des difficultés à installer Calculate Linux, ou juste pour faire part de vos impressions, n'hésitez pas à rejoindre un (ou plusieurs) des canaux <em>IRC</em> de la communauté : il suffit de cliquer sur le raccourci de <em>Xchat</em> en haut à gauche de votre bureau.</p>
<h2 id="Liens-utiles">Liens utiles<a href="#Liens-utiles" class="wiki-anchor">&para;</a></h2>
<p>Site du projet (EN): <a class="external" href="http://www.calculate-linux.org">http://www.calculate-linux.org</a><br />Notre liste de diffusion (EN) : <a class="external" href="http://www.calculate-linux.org/main/en/maillist">http://www.calculate-linux.org/main/en/maillist</a><br />Nos canaux IRC : <code>#calculate-fr</code> (en français) ou <code>#calculate</code> (en anglais) sur <em>irc.freenode.net</em></p>
<p><em>Bien à vous,<br />L'équipe Calculate Linux</em></p>
</body>
</html>

@ -1,4 +1,4 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>handbook</title>
@ -15,32 +15,29 @@ a.wiki-anchor:hover { color: #aaa !important; text-decoration: none; }
h1:hover a.wiki-anchor, h2:hover a.wiki-anchor, h3:hover a.wiki-anchor { display: inline; color: #ddd; }
pre {font-size:133% }
</style>
</head>
<body>
<h1 id="Краткое-руководство-по-установке">Краткое руководство по установке<a href="#Краткое-руководство-по-установке" class="wiki-anchor">&para;</a></h1>
<h1 id="Краткое-руководство-по-установке">Краткое руководство по установке<a href="#Краткое-руководство-по-установке" class="wiki-anchor">&para;</a></h1>
<h2 id="Благодарим-за-использование-Calculate-Linux">Благодарим за использование Calculate Linux!<a href="#Благодарим-за-использование-Calculate-Linux" class="wiki-anchor">&para;</a></h2>
<p>Мы постарались сделать для вас максимально удобную для работы систему, используя оригинальный установщик, переработанный интерфейс, шаблоны настройки, утилиты Calculate и Gentoo Portage. Дистрибутив распространяется в виде установочного образа, содержащего лучшее программное обеспечение. Большая часть программ имеет свободную лицензию, позволяющую не только устанавливать и распространять, но и модифицировать исходный код.</p>
<p>Мы постарались сделать для вас максимально удобную для работы систему, используя оригинальный установщик, переработанный интерфейс, шаблоны настройки, утилиты Calculate и Gentoo Portages. Дистрибутив распространяется в виде установочного образа, содержащего лучшее программное обеспечение. Большая часть программ имеет свободную лицензию, позволяющую не только устанавливать и распространять, но и модифицировать исходный код.</p>
Используемые сокращенные названия дистрибутивов:
<ul>
<li>CLD - Calculate Linux Desktop KDE</li>
<li>CLDC - Calculate Linux Desktop Cinnamon</li>
<li>CLDL - Calculate Linux Desktop LXQt</li>
<li>CLDM - Calculate Linux Desktop MATE</li>
<li>CLDX - Calculate Linux Desktop Xfce</li>
<li>CCM - Calculate Container Manager</li>
<li>CDS - Calculate Directory Server</li>
<li>CLD - Calculate Linux Desktop KDE</li>
<li>CLDG - Calculate Linux Desktop GNOME</li>
<li>CLDX - Calculate Linux Desktop XFCE</li>
<li>CLS - Calculate Linux Scratch</li>
<li>CMC - Calculate Media Center</li>
<li>CDS - Calculate Directory Server</li>
<li>CSS - Calculate Scratch Server</li>
</ul>
<p>Для получения прав администратора системы, запущенной с LiveCD, либо графическом режиме выполните <span class="bluecode" >su</span> в виртуальном терминале, либо перейдите в одну их текстовых консолей нажатием <strong>Ctrl+Alt+F[1-8]</strong>. Доступ к рабочему столу CLD, CLDC, CLDL, CLDM и CLDX выполняется пользователем <em>guest</em> с паролем <strong>guest</strong>.</p>
<p>Для получения прав администратора системы, запущенной с LiveCD, используйте логин <em>root</em> с паролем <strong>root</strong>. Доступ к рабочему столу CLD, CLDG и CLDX выполняется пользователем <em>guest</em> с паролем <strong>guest</strong>.</p>
<h2 id="Настройка-сети">Настройка сети<a href="#Настройка-сети" class="wiki-anchor">&para;</a></h2>
@ -54,16 +51,16 @@ pre {font-size:133% }
</ul>
<p>Подробнее в разделе <a href="https://www.calculate-linux.ru/main/ru/setup_network" target="_blank">Настройка сети</a>.</p>
<p>Подробнее в разделе <a href="http://www.calculate-linux.ru/main/ru/setup_network" class="wiki-page">Настройка сети</a>.</p>
<h2 id="Разбивка-диска">Разбивка диска<a href="#Разбивка-диска" class="wiki-anchor">&para;</a></h2>
<p>Перед установкой вам может понадобиться изменить разделы жесткого диска. Для установки CLD, CLDC, CLDL, CLDM и CLDX мы рекомендуем использовать раздел не менее 15 Гб. Более подробно аппаратные требования можно узнать <a href="https://www.calculate-linux.ru/main/ru/hardware_requirements" target="_blank">здесь</a>. Раздел подкачки (swap), как правило, выделяется вдвое большим размера оперативной памяти. Если раздел под swap уже существует, система будет использовать его. Полезно иметь отдельный раздел для личных файлов (<code>/home</code>). Наши рекомендации по разбиению диска описаны <a href="https://www.calculate-linux.ru/main/ru/disk_partitioning" target="_blank">здесь</a>.</p>
<p>Перед установкой вам может понадобиться изменить разделы жесткого диска. Для установки CLD, CLDG и CLDX мы рекомендуем использовать раздел не менее 10 Гб. Более подробно аппаратные требования можно узнать <a href="http://www.calculate-linux.ru/main/ru/hardware_requirements" class="external">здесь</a>. Раздел подкачки (swap), как правило, выделяется вдвое большим размера оперативной памяти. Если раздел под swap уже существует, система будет использовать его. Полезно иметь отдельный раздел для личных файлов (<code>/home</code>). Наши рекомендации по разбиению диска описаны <a href="http://www.calculate-linux.ru/main/ru/disk_partitioning" class="external">здесь</a>.</p>
<p>В CLD, CLDC, CLDL, CLDM и CLDX для изменения разделов диска используется программа <em>Gparted</em>. В CDS, CSS и CLS входят только консольные утилиты: <em>fdisk</em>,<em>gdisk</em> или <em>cfdisk</em>.</p>
<p>В CLD, CLDG и CLDX для изменения разделов диска используется программа <em>Gparted</em>. В CDS, CSS и CLS входят только консольные утилиты: <em>fdisk</em>,<em>gdisk</em> или <em>cfdisk</em>.</p>
<p>Чтобы просмотреть список существующих разделов, откройте консоль с правами пользователя <em>root</em> и наберите:<br /><pre>
@ -85,13 +82,13 @@ fdisk -l
Установить систему Calculate Linux вы можете одним из перечисленных способов:
<ul>
<li>графическим клиентом <a href="https://www.calculate-linux.ru/main/ru/calculate-console-gui" target="_blank">cl-console-gui</a>,</li>
<li>консольным клиентом <a href="https://www.calculate-linux.ru/main/ru/calculate-console" target="_blank">cl-console</a>,</li>
<li>напрямую сервером утилит <a href="https://www.calculate-linux.ru/main/ru/calculate-core" target="_blank">cl-core</a>.</li>
<li>графическим клиентом <a href="http://www.calculate-linux.ru/main/ru/calculate-console-gui" class="wiki-page">cl-console-gui</a>;</li>
<li>консольным клиентом <a href="http://www.calculate-linux.ru/main/ru/calculate-console" class="wiki-page">cl-console</a>;</li>
<li>используя вызов <a href="http://www.calculate-linux.ru/main/ru/calculate-core" class="wiki-page">cl-core --method=install</a>.</li>
</ul>
<p>Система может быть установлена из squashfs-образа, если Вы загрузились с liveCD или USB Flash, либо из ISO-файла, размещенного в директории <code>/var/calculate/linux</code>.</p>
<p>Система может быть установлена из squashfs-образа, если Вы загрузились с liveCD или USB Flash, либо из ISO-файла, размещенного в директории <code>/var/calculate/linux</code> или <code>/var/calculate/remote/linux</code>. Во втором случае Вы можете установить любую версию дистрибутива поддерживаемой архитектуры.</p>
<p>Сервер утилит, консольный и графический клиенты входят в состав Calculate Linux, но могут быть установлены из оверлея Calculate в любом Gentoo-совместимом дистрибутиве.</p>
@ -99,15 +96,16 @@ fdisk -l
Подробное описание установки смотрите в соответствующих разделах:
<ul>
<li><a href="https://www.calculate-linux.ru/main/ru/calculate_install" target="_blank">Установка на жёсткий диск</a></li>
<li><a href="https://www.calculate-linux.ru/main/ru/calculate_install_flash" target="_blank">Установка на Flash</a></li>
<li><a href="http://www.calculate-linux.ru/main/ru/calculate_install" class="wiki-page">Установка на жёсткий диск</a>;</li>
<li><a href="http://www.calculate-linux.ru/main/ru/calculate_install_flash" class="wiki-page">Установка на Flash</a>;</li>
<li><a href="http://www.calculate-linux.ru/main/ru/configuration_of_pxe" class="wiki-page new">Установка PXE</a>.</li>
</ul></p>
<h2 id="Первый-запуск">Первый запуск<a href="#Первый-запуск" class="wiki-anchor">&para;</a></h2>
<p>Если вы не указали других пользователей, после установки CLD, CLDC, CLDL, CLDM и CLDX в системе будут заведены две учётные записи, <em>root</em> и <em>guest</em>. Доступ к графическому сеансу может получить любой пользователь, кроме <em>root</em>. По умолчанию у пользователя <em>guest</em> установлен пароль <strong>guest</strong>.</p>
<p>Если вы не указали других пользователей, после установки CLD, CLDG и CLDX в системе будут заведены две учётные записи, <em>root</em> и <em>guest</em>. Доступ к графическому сеансу может получить любой пользователь, кроме <em>root</em>. По умолчанию у пользователя <em>guest</em> установлен пароль <strong>guest</strong>.</p>
<p>После установки в CLS нет графического приглашения к вводу пароля. Для запуска оконного менеджера выполните:<br /><pre>
@ -115,7 +113,7 @@ startx
</pre></p>
<p>Для получения прав пользователя <em>root</em> используйте команду <code>su</code>. Добавление новых пользователей подробно описано <a href="https://www.calculate-linux.ru/main/ru/create_system_users" target="_blank">здесь</a>.</p>
<p>Для получения прав пользователя <em>root</em> используйте команду <code>su</code>. Добавление новых пользователей подробно описано <a href="http://www.calculate-linux.ru/main/ru/create_system_users" class="external">здесь</a>.</p>
<p>По умолчанию вы можете зайти в систему удаленно (по протоколу ssh) только как пользователь root. В файле <code>/etc/ssh/sshd_config</code> в значение параметра <em>AllowUsers</em> можно добавить другие учётные записи. Мы рекомендуем убрать права удаленного доступа к системе для пользователя <em>root</em>.</p>
@ -124,31 +122,27 @@ startx
<h2 id="Обновление">Обновление<a href="#Обновление" class="wiki-anchor">&para;</a></h2>
<p>Calculate Linux использует rolling-release модель обновлений. Вы можете обновлять систему практически неограниченное количество раз, используя утилиту обновления системы <a href="https://wiki.calculate-linux.org/ru/system_update_guide" target="_blank">cl-update</a>.</p>
<p>Для выполнения синхронизации списка пакетов и обновления программ, выполните:<br /><pre>
cl-update
<p>Calculate Linux использует rolling-release модель обновлений. Вы можете обновлять систему практически неограниченное количество раз, используя менеджер установки программ <a href="http://www.calculate-linux.ru/main/ru/emerge" class="external">emerge</a>. Перед установкой и обновлением программ, обновите портежи:<br /><pre>
eix-sync
</pre></p>
<p>Если вы хотите только обновить список пакетов, то выполните:<br /><pre>
cl-update --sync-only
<p>Для обновления программ, выполните:<br /><pre>
emerge -uDNa world
</pre></p>
<p>После этого вы можете установить новые программы при помощи менеджера пакетов <em>emerge</em>. Краткая справка приведена <a href="https://www.calculate-linux.ru/main/ru/add_and_remove_programs" target="_blank">здесь</a>. Прочтите так же <a href="https://www.calculate-linux.ru/main/ru/system_update_guide" target="_blank">Руководство по обновлению системы</a>.</p>
<p>После этого вы можете обновить или установить новые программы при помощи менеджера пакетов <em>emerge</em>. Краткая справка приведена <a href="http://www.calculate-linux.ru/main/ru/add_and_remove_programs" class="external">здесь</a>. Прочтите так же <a href="http://www.calculate-linux.ru/main/ru/system_update_guide" class="external">Руководство по обновлению системы</a>.</p>
<h2 id="Помощь">Помощь<a href="#Помощь" class="wiki-anchor">&para;</a></h2>
<p>Если установка системы вызвала сложности или вы хотите поделиться своим впечатлением, зайдите в <em>IRC</em> чат <em>#chat-ru</em> (сервер irc.calculate.social) сообщества пользователей Calculate Linux. Для этого достаточно воспользоваться иконкой <em>Сообщество Calculate Linux</em> на вашем рабочем столе или перейдя по <a href="https://chat.calculate-linux.org/?channel=#chat-ru" target="_blank">ссылке.</a></p>
<p>Если установка системы вызвала сложности или вы хотите поделиться своим впечатлением, зайдите на <em>IRC</em> канал <em>#calculate-ru</em> (сервер FreeNode) сообщества пользователей Calculate Linux. Для этого достаточно воспользоваться иконкой <em>Xchat</em> на вашем рабочем столе.</p>
<p>Сайт проекта: <a href="https://www.calculate-linux.ru" target="_blank">https://www.calculate-linux.ru</a></p>
<p>Сайт проекта: <noindex><a class="external" href="http://www.calculate-linux.ru" ref="nofollow">http://www.calculate-linux.ru</a></noindex><br />Рассылка: <noindex><a class="external" href="http://www.calculate-linux.ru/main/ru/maillist" ref="nofollow">http://www.calculate-linux.ru/main/ru/maillist</a></noindex><br />IRC чат: <noindex><a class="external" href="http://www.calculate-linux.ru/irc" ref="nofollow">http://www.calculate-linux.ru/irc</a></noindex></p>
<p>Найти единомышленников можно и в социальных сетях:<br><a href="https://calculate.social/@news_ru" target="_blank">Mastodon</a>, <a href="https://vk.com/calculatelinux" target="_blank">ВКонтакте</a>, <a href="https://www.facebook.com/CalculateLinux.ru">Facebook</a> или <a href="https://www.ok.ru/calculate" target="_blank">Одноклассники</a>.</p>
<p><em>Приятной работы!<br />Команда разработчиков Calculate Linux.</em></p>
</body>

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2010-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2010-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -17,13 +17,12 @@
__app__ = 'calculate-install'
__version__ = '3.1.8'
import os
import sys
from calculate.lib.datavars import DataVars
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3', sys.modules[__name__])
setLocalTranslate('cl_install3',sys.modules[__name__])
class DataVarsInstall(DataVars):
"""Variable class for installation"""

File diff suppressed because it is too large Load Diff

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2010-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2010-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -14,197 +14,141 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import re
import sys
import time
import traceback
from os import path
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
setLocalTranslate('cl_install3', sys.modules[__name__])
class FileSystemManager():
class FileSystemManager:
"""Convert dict install option"""
defaultOpt = ['noatime']
defaultBindOpts = ['bind']
#Python3 compat problem:
# dict keys() now sorted based on insertion order,
# instead of being sorted arbitrary by hash.
# Just so the order of keys could be the same as
# in older version, I swaped some pairs around.
supportFS = {
'f2fs': {'defaultopt': defaultOpt,
'format': '/usr/sbin/mkfs.f2fs',
'formatparam': '{labelparam} -f {device}',
'gpt': '8300',
'label': '-l {labelname}',
'msdos': '83',
'ssd': [],
'compress': None,
'type': ['hdd', 'usb-hdd']},
'btrfs': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.btrfs',
'formatparam': '{labelparam} -f {device}',
'ext2': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext2',
'formatparam': '{labelparam} {device}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '83',
'ssd': ['ssd'],
'type': ['hdd', 'usb-hdd'],
'compress': None,
'compatible': ['btrfs-compress']},
'ntfs-3g': {'defaultopt': defaultOpt,
'format': '/usr/sbin/mkfs.ntfs',
'formatparam': '{labelparam} -FQ {device}',
'gpt': '8300',
'label': '-L {labelname}',
'ssd': [],
'auto': False,
'msdos': '7',
'compress': None,
'compatible': ['ntfs']},
'ntfs': {'defaultopt': defaultOpt,
'format': '/usr/sbin/mkfs.ntfs',
'formatparam': '{labelparam} -FQ {device}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '7',
'auto': False,
'ssd': [],
'compress': None,
'compatible': ['ntfs-3g']},
'xfs': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.xfs',
'formatparam': '{labelparam} -f {device}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '83',
'boot': '-i sparce=0',
'ssd': [],
'compress': None,
'type': ['hdd', 'usb-hdd']},
'btrfs-compress': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.btrfs',
'orig': 'btrfs',
'compress': "compress=%s",
'formatparam': '{labelparam} -f {device}',
'type':['hdd','usb-hdd']},
'ext3': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext3',
'formatparam': '{labelparam} {device}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '83',
'ssd': ['ssd'],
'type': ['hdd', 'usb-hdd'],
'compatible': ['btrfs']},
'ext4': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext4',
'formatparam': '{labelparam} {device}',
'gpt': '8300',
'label': '-L {labelname}',
'ssd': [],
'msdos': '83',
'compress': None,
'type': ['hdd', 'usb-hdd']},
'ext3': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext3',
'formatparam': '{labelparam} {device}',
'type':['hdd','usb-hdd']},
'ext4': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext4',
'formatparam': '{labelparam} {device}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '83',
'type':['hdd','usb-hdd']},
'reiserfs': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.reiserfs',
'formatparam': '{labelparam} -f {device}',
'gpt': '8300',
'label': '-l {labelname}',
'msdos': '83',
'type':['hdd','usb-hdd']},
'btrfs': {'defaultopt': defaultOpt,
'format':'/sbin/mkfs.btrfs',
'formatparam': '{labelparam} -f {device}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '83',
'type':['hdd','usb-hdd']},
'jfs': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.jfs',
'formatparam': '{labelparam} -f {device}',
'gpt': '8300',
'label': '-L {labelname}',
'ssd': [],
'msdos': '83',
'compress': None,
'type': ['hdd', 'usb-hdd']},
'ext2': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext2',
'formatparam': '{labelparam} {device}',
'type':['hdd','usb-hdd']},
'xfs': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.xfs',
'formatparam': '{labelparam} -f {device}',
'gpt': '8300',
'label': '-L {labelname}',
'ssd': [],
'msdos': '83',
'compress': None,
'type': ['hdd', 'usb-hdd']},
'uefi': {'defaultopt': defaultOpt,
'format': '/usr/sbin/mkfs.vfat',
'formatparam': '{labelparam} -F 32 {device}',
'gpt': 'EF00',
'label': '-n {labelname}',
'msdos': '0b',
'ssd': [],
'auto': False,
'compress': None,
'type': ['hdd']},
'vfat': {'defaultopt': defaultOpt,
'format': '/usr/sbin/mkfs.vfat',
'formatparam': '{labelparam} -F 32 {device}',
'gpt': '0700',
'label': '-n {labelname}',
'msdos': '0b',
'auto': False,
'ssd': [],
'compress': None,
'type': ['flash']},
'jfs': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.jfs',
'formatparam': '{labelparam} -f {device}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '83',
'ssd': [],
'compress': None,
'type': ['hdd', 'usb-hdd']},
# 'nilfs2': {'defaultopt': defaultOpt,
# 'format': '/sbin/mkfs.nilfs2',
# 'formatparam': '{labelparam} {device}',
# 'gpt': '8300',
# 'label': '-L {labelname}',
# 'msdos': '83',
# 'ssd': [],
# 'type': ['hdd', 'usb-hdd']},
'swap': {'defaultopt': ['sw'],
'format': '/sbin/mkswap',
'formatparam': '{device}',
'gpt': '8200',
'label': '',
'ssd': [],
'auto': False,
'compress': None,
'msdos': '82'},
}
default_param = {'defaultopt': defaultOpt,
'type':['hdd','usb-hdd']},
'nilfs2': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.nilfs2',
'formatparam': '{labelparam} {device}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '83',
'type':['hdd','usb-hdd']},
'swap': {'defaultopt': 'sw',
'format': '/sbin/mkswap',
'formatparam': '{device}',
'gpt': '8200',
'label': '',
'msdos': '82'},
'uefi': {'defaultopt': defaultOpt,
'format': '/usr/sbin/mkfs.vfat',
'formatparam': '{labelparam} -F 32 {device}',
'gpt': 'EF00',
'label': '-n {labelname}',
'msdos': '0b',
'type':['hdd']},
'vfat': {'defaultopt': defaultOpt,
'format': '/usr/sbin/mkfs.vfat',
'formatparam': '{labelparam} -F 32 {device}',
'gpt': '0700',
'label': '-n {labelname}',
'msdos': '0b',
'type':['flash']},
'ntfs': {'defaultopt': defaultOpt,
'format': '/usr/sbin/mkfs.ntfs',
'formatparam': '{labelparam} -FQ {device}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '7',
'compatible':['ntfs-3g']},
'ntfs-3g': {'defaultopt': defaultOpt,
'format': '/usr/sbin/mkfs.ntfs',
'formatparam': '{labelparam} -FQ {device}',
'gpt': '8300',
'msdos': '83',
'compress': None,
'ssd': []}
'label': '-L {labelname}',
'msdos': '7',
'compatible':['ntfs']}}
@classmethod
def firstAvailable(cls, listFS):
def firstAvailable(cls,listFS):
for fs in listFS:
if path.exists(cls.supportFS['format']):
return fs
else:
return ""
@classmethod
def get_default_fs(cls, dv, installtype):
if installtype == 'flash':
return 'vfat'
filesystems = dv.Get('install.cl_install_fs')
for fs in filesystems:
if fs in cls.supportFS and path.exists(cls.supportFS[fs]['format']):
return fs
return 'ext3'
defaultFS = {'hdd':"ext4" \
if path.exists(supportFS['ext4']['format']) else \
"reiserfs" \
if path.exists(supportFS['reiserfs']['format']) else \
"ext3",
'flash':"vfat",
'usb-hdd': "ext4" \
if path.exists(supportFS['ext4']['format']) else \
"reiserfs" \
if path.exists(supportFS['reiserfs']['format']) else \
"ext3"}
@classmethod
def getDefaultOpt(cls, fs, ssd=False, compress=None):
fsopts = cls.supportFS.get(fs, cls.default_param)
return ",".join(fsopts['defaultopt'] +
(fsopts['ssd'] if ssd else []) +
([fsopts['compress'] % compress]
if fsopts['compress'] and compress else []))
def getDefaultOpt(cls,fs):
return ",".join(cls.supportFS.get(fs,{'defaultopt':[]})['defaultopt'])
@classmethod
def checkFSForTypeMount(cls, fs, roottype, mp):
if mp.startswith('/boot/efi'):
if fs not in ('uefi', 'vfat'):
def checkFSForTypeMount(cls,fs,roottype,mp):
if mp == '/boot/efi':
if not fs in ('uefi','vfat'):
return False
else:
return True
return roottype in cls.supportFS.get(fs, {}).get('type', [])
return roottype in cls.supportFS.get(fs,{}).get('type',[])

File diff suppressed because it is too large Load Diff

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2010-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2010-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -17,30 +17,22 @@
import os, sys, re, time
from calculate.lib.encrypt import encrypt
from os import path
from calculate.lib.utils.files import pathJoin, FilePermission
from calculate.lib.cl_lang import setLocalTranslate, _
from functools import reduce
setLocalTranslate('cl_install3', sys.modules[__name__])
from calculate.lib.utils.files import pathJoin
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
class MigrationError(Exception):
pass
class _shareData():
class _shareData:
"""Share class"""
_reNumb = re.compile("^\d+$")
def getDataInFile(self, fileName='', lenData=7):
"""Get data list from file"""
with open(fileName) as f:
return [x[:lenData] for x
in (y.rstrip().split(":") for y
in f)
if len(x) >= lenData]
return filter(lambda x: len(x)==lenData,
map(lambda x: x.rstrip().split(":"), open(fileName)))
class migrateGroups(_shareData):
"""Migrate group to new system"""
@ -59,43 +51,46 @@ class migrateGroups(_shareData):
def getThisData(self):
"""Get data migrate groups in this system"""
return [x for x in self.getData()
if self._reNumb.match(x[2]) and self.minGid <= int(x[2]) <= self.maxGid]
return filter(lambda x:\
self._reNumb.match(x[2]) and self.minGid<=int(x[2])<=self.maxGid,
self.getData())
def getNewData(self):
"""Get data migrate groups in new system"""
fileName = pathJoin(self.prefixNewSystem, self.fileGroups)
return [x for x in self.getData(fileName=fileName)
if self._reNumb.match(x[2]) and self.minGid <= int(x[2]) <= self.maxGid]
return filter(lambda x:\
self._reNumb.match(x[2]) and self.minGid<=int(x[2])<=self.maxGid,
self.getData(fileName=fileName))
def getNewDataSystemGroups(self):
"""Get data system groups in new system"""
fileName = pathJoin(self.prefixNewSystem, self.fileGroups)
return [x for x in self.getData(fileName=fileName)
if self._reNumb.match(x[2]) and (int(x[2]) > self.maxGid or int(x[2]) < self.minGid)]
return filter(lambda x:\
self._reNumb.match(x[2]) and\
(int(x[2])>self.maxGid or int(x[2])<self.minGid),
self.getData(fileName=fileName))
def getNewProcessedData(self):
"""Get processed data migrate groups in new system"""
# data this Group no users
dataThisGroupsNoUsers = [x[:3] + [""] for x in self.getThisData()]
dataThisGroupsNoUsers = map(lambda x: x[:3]+[""], self.getThisData())
dataNewGroups = self.getNewData()
namesNewGroups = [x[0] for x in dataNewGroups]
gidsNewGroups = [x[2] for x in dataNewGroups]
namesNewGroups = map(lambda x: x[0], dataNewGroups)
gidsNewGroups = map(lambda x: x[2], dataNewGroups)
for data in dataThisGroupsNoUsers:
nameGroup = data[0]
gid = data[2]
if nameGroup in namesNewGroups:
dataNewGroups = [x for x in dataNewGroups if x[0] != nameGroup]
namesNewGroups = [x[0] for x in dataNewGroups]
gidsNewGroups = [x[2] for x in dataNewGroups]
dataNewGroups = filter(lambda x: x[0]!=nameGroup,dataNewGroups)
namesNewGroups = map(lambda x: x[0], dataNewGroups)
gidsNewGroups = map(lambda x: x[2], dataNewGroups)
if gid in gidsNewGroups:
dataNewGroups = [x for x in dataNewGroups if x[2] != gid]
namesNewGroups = [x[0] for x in dataNewGroups]
gidsNewGroups = [x[2] for x in dataNewGroups]
dataNewGroups = filter(lambda x: x[2]!=gid, dataNewGroups)
namesNewGroups = map(lambda x: x[0], dataNewGroups)
gidsNewGroups = map(lambda x: x[2], dataNewGroups)
systemGroupsNewData = self.getNewDataSystemGroups()
return systemGroupsNewData, dataNewGroups, dataThisGroupsNoUsers
class migrateUsers(_shareData):
"""Migrate users to new system"""
@ -113,71 +108,82 @@ class migrateUsers(_shareData):
def getThisData(self):
"""Get data migrate users in this system"""
return [x for x in self.getData()
if self._reNumb.match(x[2]) and self.minId <= int(x[2]) <= self.maxId]
return filter(lambda x:\
self._reNumb.match(x[2]) and self.minId<=int(x[2])<=self.maxId,
self.getData())
def getNewData(self):
"""Get data migrate users in new system"""
fileName = pathJoin(self.prefixNewSystem, self.filePasswd)
return [x for x in self.getData(fileName=fileName)
if self._reNumb.match(x[2]) and self.minId <= int(x[2]) <= self.maxId]
return filter(lambda x:\
self._reNumb.match(x[2]) and self.minId<=int(x[2])<=self.maxId,
self.getData(fileName=fileName))
def getNewDataSystemUsers(self):
"""Get data system users in new system"""
fileName = pathJoin(self.prefixNewSystem, self.filePasswd)
return [x for x in self.getData(fileName=fileName)
if self._reNumb.match(x[2]) and (int(x[2]) > self.maxId or int(x[2]) < self.minId)]
return filter(lambda x:\
self._reNumb.match(x[2]) and\
(int(x[2]>self.maxId) or int(x[2])<self.minId),
self.getData(fileName=fileName))
def getThisDataSystemUsers(self):
"""Get data system users in this system"""
fileName = self.filePasswd
return [x for x in self.getData(fileName=fileName)
if self._reNumb.match(x[2]) and (int(x[2]) > self.maxId or int(x[2]) < self.minId)]
return filter(lambda x:\
self._reNumb.match(x[2]) and\
(int(x[2]>self.maxId) or int(x[2])<self.minId),
self.getData(fileName=fileName))
def getNewProcessedData(self, migrateUsers=()):
def getNewProcessedData(self, migrateUsers=[]):
"""Get processed data migrate users in new system"""
dataThisUsers = self.getThisData()
if migrateUsers:
dataThisUsers = [x for x in dataThisUsers if x[0] in migrateUsers]
dataThisUsers = filter(lambda x: x[0] in migrateUsers,
dataThisUsers)
dataNewUsers = self.getNewData()
namesNewUsers = [x[0] for x in dataNewUsers]
uidsNewUsers = [x[2] for x in dataNewUsers]
namesNewUsers = map(lambda x: x[0], dataNewUsers)
uidsNewUsers = map(lambda x: x[2], dataNewUsers)
for data in dataThisUsers:
nameUser = data[0]
uid = data[2]
if nameUser in namesNewUsers:
dataNewUsers = [x for x in dataNewUsers if x[0] != nameUser]
namesNewUsers = [x[0] for x in dataNewUsers]
uidsNewUsers = [x[2] for x in dataNewUsers]
dataNewUsers = filter(lambda x: x[0]!=nameUser, dataNewUsers)
namesNewUsers = map(lambda x: x[0], dataNewUsers)
uidsNewUsers = map(lambda x: x[2], dataNewUsers)
if uid in uidsNewUsers:
dataNewUsers = [x for x in dataNewUsers if x[2] != uid]
namesNewUsers = [x[0] for x in dataNewUsers]
uidsNewUsers = [x[2] for x in dataNewUsers]
dataNewUsers = filter(lambda x: x[2]!=uid, dataNewUsers)
namesNewUsers = map(lambda x: x[0], dataNewUsers)
uidsNewUsers = map(lambda x: x[2], dataNewUsers)
systemUsersNewData = self.getNewDataSystemUsers()
systemUsersNewNames = [x[0] for x in systemUsersNewData]
systemUsersNewUids = [x[2] for x in systemUsersNewData]
systemUsersNewNames = map(lambda x: x[0], systemUsersNewData)
systemUsersNewUids = map(lambda x: x[2], systemUsersNewData)
systemUsersThisData = []
if migrateUsers:
# this users < minId
systemUsersThisData = [x for x in self.getThisDataSystemUsers()
if int(x[2]) < self.minId and x[0] in migrateUsers]
systemUsersThisData = filter(lambda x: int(x[2])<self.minId and\
x[0] in migrateUsers,
self.getThisDataSystemUsers())
for data in systemUsersThisData:
nameUser = data[0]
uid = data[2]
if nameUser in systemUsersNewNames:
systemUsersNewData = [x for x in systemUsersNewData
if x[0] != nameUser]
systemUsersNewNames = [x[0] for x in systemUsersNewData]
systemUsersNewUids = [x[2] for x in systemUsersNewData]
systemUsersNewData = filter(lambda x: x[0]!=nameUser,
systemUsersNewData)
systemUsersNewNames = map(lambda x: x[0],
systemUsersNewData)
systemUsersNewUids = map(lambda x: x[2],
systemUsersNewData)
if uid in systemUsersNewUids:
systemUsersNewData = [x for x in systemUsersNewData
if x[2] != uid]
systemUsersNewNames = [x[0] for x in systemUsersNewData]
systemUsersNewUids = [x[2] for x in systemUsersNewData]
systemUsersNewData = filter(lambda x: x[2]!=uid,
systemUsersNewData)
systemUsersNewNames = map(lambda x: x[0],
systemUsersNewData)
systemUsersNewUids = map(lambda x: x[2],
systemUsersNewData)
return (systemUsersThisData, systemUsersNewData,
dataNewUsers, dataThisUsers)
class migrateShadow(_shareData):
"""Migrate users to new system"""
@ -199,52 +205,49 @@ class migrateShadow(_shareData):
def getThisData(self):
"""Get data migrate users in this system"""
return [x for x in self.getData()
if x[0] in self.thisMigrateUsers]
return filter(lambda x: x[0] in self.thisMigrateUsers, self.getData())
def getNewData(self):
"""Get data migrate users in new system"""
return [x for x in self.getData(fileName=self.newFileName)
if x[0] in self.newMigrateUsers]
return filter(lambda x: x[0] in self.newMigrateUsers,
self.getData(fileName=self.newFileName))
def getNewDataSystemShadow(self):
"""Get data system users in new system"""
return [x for x in self.getData(fileName=self.newFileName)
if x[0] in self.sysNewMigrateUsers]
return filter(lambda x: x[0] in self.sysNewMigrateUsers,
self.getData(fileName=self.newFileName))
def getThisDataSystemShadow(self):
"""Get data system users in this system"""
return [x for x in self.getData() if x[0] in self.sysThisMigrateUsers]
return filter(lambda x: x[0] in self.sysThisMigrateUsers,self.getData())
def getNewProcessedData(self):
"""Get processed data migrate shadow in new system"""
dataThisShadow = self.getThisData()
dataNewShadow = self.getNewData()
namesNewShadow = [x[0] for x in dataNewShadow]
namesNewShadow = map(lambda x: x[0], dataNewShadow)
for data in dataThisShadow:
nameUser = data[0]
if nameUser in namesNewShadow:
dataNewShadow = [x for x in dataNewShadow if x[0] != nameUser]
namesNewShadow = [x[0] for x in dataNewShadow]
dataNewShadow = filter(lambda x: x[0]!=nameUser, dataNewShadow)
namesNewShadow = map(lambda x: x[0], dataNewShadow)
systemShadowNewData = self.getNewDataSystemShadow()
systemShadowThisData = self.getThisDataSystemShadow()
systemShadowNewNames = [x[0] for x in systemShadowNewData]
systemShadowNewNames = map(lambda x: x[0], systemShadowNewData)
for data in systemShadowThisData:
nameUser = data[0]
if nameUser in systemShadowNewNames:
systemShadowNewData = [x for x
in systemShadowNewData if x[0] != nameUser]
systemShadowNewNames = [x[0] for x in systemShadowNewData]
systemShadowNewData = filter(lambda x: x[0]!=nameUser,
systemShadowNewData)
systemShadowNewNames = map(lambda x: x[0], systemShadowNewData)
return (systemShadowThisData, systemShadowNewData, dataNewShadow,
dataThisShadow)
class migrate():
class migrate:
"""Migrate users ang groups to new system"""
templateShadow = "%(user)s:%(hash)s:%(days)s:0:%(maxDays)s:%(warnDays)s:::"
templateUser = "%(user)s:x:%(id)s:%(gid)s::/home/%(user)s:/bin/bash"
templateGroup = "%(group)s:x:%(gid)s:"
templateUser="%(user)s:x:%(id)s:%(gid)s::/home/%(user)s:/bin/bash"
templateGroup="%(group)s:x:%(gid)s:"
dataUsers = []
dataGroups = []
dataShadow = []
@ -254,8 +257,8 @@ class migrate():
minGid = 1000
minSysId = 1000
newUserGroups = ["audio", "cdrom", "cdrw", "games", "lp", "lpadmin",
"plugdev", "scanner" "usb", "users", "video", "wheel"]
newUserGroups = ["audio", "cdrom", "cdrw", "games", "lp", "plugdev",
"scanner" "usb", "users", "video", "wheel"]
def __init__(self, prefixNewSystem):
self.prefixNewSystem = prefixNewSystem
@ -265,43 +268,50 @@ class migrate():
def addThisUsersToGroups(self, users):
"""Add users to groups"""
thisGroupsData = self.objGroups.getData()
thisGroupsData = [(x[0], x[3].split(',')) for x in thisGroupsData]
thisGroupsData = map(lambda x: (x[0],x[3].split(',')),
thisGroupsData)
dataGroups = []
for data in self.dataGroups:
groupName = data[0]
thisUsersInGroup = [x[1] for x in thisGroupsData if x[0] == groupName]
#??? whats the point of this?
thisUsersInGroup = reduce(lambda x, y: x + y, thisUsersInGroup, [])
addUsers = list(set(thisUsersInGroup) & set(users))
thisUsersInGroup = map(lambda x: x[1],
filter(lambda x: x[0]==groupName, thisGroupsData))
thisUsersInGroup = reduce(lambda x,y: x+y, thisUsersInGroup,[])
addUsers = list(set(thisUsersInGroup)&set(users))
if addUsers:
newUsersInGroup = data[3].split(',')
for user in addUsers:
if not user in newUsersInGroup:
newUsersInGroup.append(user)
data[3] = ','.join((x for x in newUsersInGroup if x))
data[3] = ','.join(filter(lambda x:x,newUsersInGroup))
dataGroups.append(data)
self.dataGroups = dataGroups
return self.dataGroups
def getNextUid(self):
"""get next uid"""
listUid = [int(x[2]) for x in self.dataUsers
if self.objUsers._reNumb.match(x[2]) and self.minId <= int(x[2]) <= self.maxId]
listUid = map(lambda x: int(x[2]),
filter(lambda x:\
self.objUsers._reNumb.match(x[2]) and\
self.minId<=int(x[2])<=self.maxId,
self.dataUsers))
if listUid:
return max(listUid) + 1
return max(listUid)+1
return self.minId
def getNextGid(self):
"""get next gid"""
listGid = [int(x[2]) for x in self.dataGroups
if self.objUsers._reNumb.match(x[2]) and self.minGid <= int(x[2]) <= self.maxGid]
listGid = map(lambda x: int(x[2]),
filter(lambda x:\
self.objGroups._reNumb.match(x[2]) and\
self.minGid<=int(x[2])<=self.maxGid,
self.dataGroups))
if listGid:
return max(listGid) + 1
return max(listGid)+1
return self.minGid
def isSystemUser(self, userName):
if [x for x in self.dataUsers
if (x[0] == userName and int(x[2]) <= self.minSysId)]:
if filter(lambda x: x[0]==userName and int(x[2])<=self.minSysId,
self.dataUsers):
return True
return False
@ -315,33 +325,34 @@ class migrate():
usersInGroup = data[3].split(',')
if not userName in usersInGroup:
usersInGroup.append(userName)
data[3] = ','.join((x for x in usersInGroup if x))
data[3] = ','.join(filter(lambda x:x,usersInGroup))
dataGroups.append(data)
self.dataGroups = dataGroups
return self.dataGroups
def addUserToDefaultGroups(self, userName):
"""Add users to default groups"""
return self.addUserToGroups(userName, self.newUserGroups)
return self.addUserToGroups(userName,self.newUserGroups)
def changePassword(self, userName, pwdHash, maxDays="99999", warnDays="7"):
if not [x for x in self.dataUsers if x[0] == userName]:
raise MigrationError(_("User %s not found") % userName)
if not filter(lambda x: x[0]==userName, self.dataUsers):
raise MigrationError(_("User %s not found")%userName)
indexFoundUser = False
for i, data in enumerate(self.dataShadow):
if data[0] == userName:
if data[0]==userName:
indexFoundUser = i
break
if callable(pwdHash):
pwdHash = pwdHash(userName)
if pwdHash is False:
return False
shadowDict = {"user": userName,
"hash": pwdHash,
"days": str(int(time.time() / 86400)),
"maxDays": maxDays,
"warnDays": warnDays}
shadowLine = self.templateShadow % shadowDict
shadowDict = {"user":userName,
"hash":pwdHash,
"days":str(int(time.time()/86400)),
"maxDays":maxDays,
"warnDays":warnDays}
shadowLine = self.templateShadow %shadowDict
shadowList = shadowLine.split(":")
if indexFoundUser is False:
self.dataShadow.append(shadowList)
@ -352,81 +363,80 @@ class migrate():
def addUser(self, userName, userGroups, pwdHash):
"""Add user"""
# find user
if [x for x in self.dataUsers if x[0] == userName]:
if filter(lambda x: x[0]==userName, self.dataUsers):
return "EXISTS"
else:
strUid = str(self.getNextUid())
strGid = str(self.getNextGid())
groupName = userName
dataExistGroup = [x for x in self.dataGroups
if x[0] == groupName]
dataExistGroup = filter(lambda x: x[0]==groupName, self.dataGroups)
if dataExistGroup:
strGid = dataExistGroup[0][2]
else:
# add group
groupDict = {"group": groupName, "gid": strGid}
groupLine = self.templateGroup % groupDict
groupDict = {"group":groupName,"gid":strGid}
groupLine = self.templateGroup %groupDict
groupList = groupLine.split(":")
self.dataGroups.append(groupList)
# add user
userDict = {"user": userName, "id": strUid, "gid": strGid}
userline = self.templateUser % userDict
userDict = {"user":userName, "id":strUid, "gid":strGid}
userline = self.templateUser %userDict
userList = userline.split(":")
self.dataUsers.append(userList)
# add shadow
if not self.changePassword(userName, pwdHash):
return False
# add user to default groups
self.addUserToGroups(userName, userGroups)
self.addUserToGroups(userName,userGroups)
return True
def checkPermFiles(self):
"""Check permission files"""
checkThisFiles = [migrateGroups.fileGroups, migrateUsers.filePasswd,
migrateShadow.fileShadow]
checkNewFiles = [pathJoin(self.prefixNewSystem, x) for x in checkThisFiles]
checkNewFiles = map(lambda x: pathJoin(self.prefixNewSystem,x),
checkThisFiles)
parentDir = lambda x: "".join(os.path.split(x)[:-1])
notRead = lambda x: not os.access(x, os.R_OK)
notWrite = lambda x: not os.access(x, os.W_OK)
filesNotRead = [x for x in checkThisFiles if notRead(x)]
filesNotRead = filter(notRead,checkThisFiles)
if filesNotRead:
raise MigrationError(_("Failed to read files") + _(": ") +
", ".join(filesNotRead))
filesNotWrite = [x for x in checkNewFiles if notWrite(x)]
", ".join(filesNotRead))
filesNotWrite = filter(notWrite,checkNewFiles)
if filesNotWrite:
raise MigrationError(_("Failed to write to files") + _(": ") +
", ".join(filesNotWrite))
", ".join(filesNotWrite))
# Check permissions backup files
checkNewBackupFiles = (pathJoin(self.prefixNewSystem, x + "-") for x
in checkThisFiles)
checkNewBackupFiles = map(lambda x:pathJoin(self.prefixNewSystem,x+"-"),
checkThisFiles)
notWriteBackup = lambda x: not os.access(x, os.W_OK) and \
(os.path.exists(x) or
(os.path.exists(x) or \
not os.access(os.path.dirname(x), os.W_OK))
filesNotWrite = [x for x in checkNewBackupFiles if notWriteBackup(x)]
filesNotWrite = filter(notWriteBackup, checkNewBackupFiles)
if filesNotWrite:
raise MigrationError(_("Failed to write to files") + _(": ") +
", ".join(filesNotWrite))
", ".join(filesNotWrite))
return True
def saveNewFiles(self):
"""Save /etc/passwd /etc/group /etc/shadow to new system"""
listFilesThisSystem = [migrateGroups.fileGroups,
migrateUsers.filePasswd,
listFilesThisSystem = [migrateGroups.fileGroups,migrateUsers.filePasswd,
migrateShadow.fileShadow]
listFiles = [(pathJoin(self.prefixNewSystem, x),
pathJoin(self.prefixNewSystem, x + "-")) for x
in listFilesThisSystem]
listFiles = map(lambda x:(pathJoin(self.prefixNewSystem,x),
pathJoin(self.prefixNewSystem,x+"-")),
listFilesThisSystem)
listData = [self.dataGroups, self.dataUsers, self.dataShadow]
allData = zip(listFiles, listData)
allData = zip(listFiles,listData)
for fileNames, data in allData:
buff = "\n".join((":".join(x) for x in data)) + "\n"
buff = "\n".join(map(lambda x: ":".join(x), data)) + "\n"
for fileName in fileNames:
FD = open(fileName, "w+")
FD = open(fileName, "w+")
FD.write(buff)
FD.close()
def createUserGuest(self):
if [x for x in self.dataUsers if int(x[2]) >= self.minSysId]:
if filter(lambda x: int(x[2])>=self.minSysId, self.dataUsers):
return True
else:
# add user guest
@ -435,68 +445,58 @@ class migrate():
pwdHash = encryptObj.getHashPasswd(pwd, "shadow_ssha256")
if pwdHash is False:
return False
if not self.addUser("guest", "guest", pwdHash):
if not self.addUser("guest", pwdHash):
return False
return True
def createHomeDirs(self, addUsersList, existsMigrateUsers):
def createHomeDirs(self,addUsersList,existsMigrateUsers):
"""Create home directories for all migreate users"""
def createHome(userdata):
perms = FilePermission.UserAll
if not userdata[5].startswith('/dev/'):
homedir = pathJoin(self.prefixNewSystem, userdata[5])
homedir = pathJoin(self.prefixNewSystem,userdata[5])
if not path.exists(homedir):
os.mkdir(homedir)
os.chown(homedir, int(userdata[2]), int(userdata[3]))
os.chmod(homedir, perms)
users = list(set([x[0] for x in addUsersList] + existsMigrateUsers) - {"root"})
os.chown(homedir,int(userdata[2]),int(userdata[3]))
users = list(set(map(lambda x:x[0],addUsersList)+existsMigrateUsers)-\
set(["root"]))
try:
# map(createHome, (x for x in self.dataUsers if x[0] in users))
[createHome(x) for x in self.dataUsers if x[0] in users]
except Exception as e:
raise MigrationError(
map(createHome,filter(lambda x:x[0] in users, self.dataUsers))
except Exception,e:
raise DistributiveError(
_("Failed to create the user's home directory"))
def migrate(self, addUsersList=None, rootPwd="",
pwdUsersList=None, existsMigrateUsers=None):
def migrate(self, addUsersList=[], rootPwd="",
pwdUsersList=[], existsMigrateUsers=[]):
"""Migrate users ang groups to new system"""
if addUsersList is None:
addUsersList = []
elif not any(addUsersList):
addUsersList = []
if pwdUsersList is None:
pwdUsersList = []
if existsMigrateUsers is None:
existsMigrateUsers = []
if not self.checkPermFiles():
return False
migrateUsers = (["root"] + [x[0] for x in addUsersList + pwdUsersList])
if not any(addUsersList):
addUsersList = []
migrateUsers = ["root"]+\
map(lambda x: x[0], addUsersList + pwdUsersList)
for existMigrUser in existsMigrateUsers:
if existMigrUser not in migrateUsers:
if not existMigrUser in migrateUsers:
migrateUsers.append(existMigrUser)
# add root to migrate users
dataUsers = self.objUsers.getNewProcessedData(migrateUsers)
dataGroups = self.objGroups.getNewProcessedData()
thisSystemUsers, newSystemUsers, newUsers, thisUsers = \
[[y[0] for y in x] for x in dataUsers]
thisSystemUsers, newSystemUsers, newUsers, thisUsers =\
map(lambda x: map(lambda y: y[0],x), dataUsers)
objShadow = migrateShadow(thisSystemUsers, newSystemUsers, newUsers,
thisUsers, self.prefixNewSystem)
dataShadow = objShadow.getNewProcessedData()
self.dataGroups = reduce(lambda x, y: x + y, dataGroups, [])
self.dataUsers = reduce(lambda x, y: x + y, dataUsers, [])
self.dataShadow = reduce(lambda x, y: x + y, dataShadow, [])
self.dataGroups = reduce(lambda x,y: x+y, dataGroups, [])
self.dataUsers = reduce(lambda x,y: x+y, dataUsers, [])
self.dataShadow = reduce(lambda x,y: x+y, dataShadow, [])
self.addThisUsersToGroups(thisUsers)
for userName, pwdHash, maxDays, warnDays in pwdUsersList:
if not self.changePassword(userName, pwdHash,
maxDays=maxDays,
warnDays=warnDays):
return False
for userName, userGroups, pwdHash in [
["root", [], rootPwd]] + addUsersList:
# if self.isSystemUser(userName):
for userName, userGroups, pwdHash in [["root",[],rootPwd]]+addUsersList:
#if self.isSystemUser(userName):
# raise MigrationError(_("%s is a system user") %userName)
ret = self.addUser(userName, userGroups, pwdHash)
if not ret:
@ -509,17 +509,17 @@ class migrate():
if not self.createUserGuest():
return False
self.saveNewFiles()
self.createHomeDirs(addUsersList, existsMigrateUsers)
self.createHomeDirs(addUsersList,existsMigrateUsers)
return True
class currentUsers(migrate):
"""Current users"""
def __init__(self):
super().__init__('/')
self.prefixNewSystem = '/'
self.objGroups = migrateGroups(self.prefixNewSystem)
self.objUsers = migrateUsers(self.prefixNewSystem)
def addUsers(self, *users_passwd):
def addUsers(self,*users_passwd):
"""Added users and groups to current system"""
if not self.checkPermFiles():
return False
@ -533,16 +533,17 @@ class currentUsers(migrate):
getHash = encrypt().getHashPasswd
for userName, pwd in zip(users_passwd[0::2],
users_passwd[1::2]):
pwdHash = getHash(pwd, "shadow_ssha256")
if not self.addUser(userName, userName, pwdHash):
pwdHash = getHash(pwd,"shadow_ssha256")
if not self.addUser(userName, pwdHash):
return False
self.saveNewFiles()
return True
def hasUsers(self, *users):
def hasUsers(self,*users):
"""Is users in system"""
if not self.checkPermFiles():
return False
getDataInFile = _shareData().getDataInFile
self.dataUsers = [x[0] for x in getDataInFile(fileName=migrateUsers.filePasswd,lenData=7)]
self.dataUsers = map(lambda x:x[0],
getDataInFile(fileName=migrateUsers.filePasswd,lenData=7))
return set(self.dataUsers) >= set(users)

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2010-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2010-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -15,153 +15,142 @@
# limitations under the License.
import sys
from calculate.core.server.func import Action, Tasks
from ..distr import DistributiveError
from ..migrate_users import MigrationError
from ..variables.autopartition import AutopartitionError
from calculate.lib.utils.partition import VolumesError
from calculate.lib.cl_lang import setLocalTranslate, getLazyLocalTranslate, _
from calculate.lib.cl_template import TemplatesError
from calculate.core.server.func import Action,Tasks
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
from calculate.lib.utils.files import FilesError
from ..install import InstallError
from calculate.install.install import (MigrationError, TemplatesError,
InstallError,
AutopartitionError, DistributiveError)
setLocalTranslate('cl_install3', sys.modules[__name__])
setLocalTranslate('cl_install3',sys.modules[__name__])
__ = getLazyLocalTranslate(_)
class ClInstallAction(Action):
"""
Установка системы
"""
# ошибки, которые отображаются без подробностей
native_error = (FilesError, MigrationError, TemplatesError, VolumesError,
InstallError, AutopartitionError, DistributiveError)
native_error = (FilesError,MigrationError, TemplatesError,
InstallError, AutopartitionError, DistributiveError)
successMessage = None
failedMessage = None
interruptMessage = None
# список задач для действия
tasks = [
# авторазметка диска
{'name': 'autopartition',
'message': __("Creating a new partition table"),
'method': "Install.autopartition(cl_autopartition_scheme_builder,"
"cl_autopartition_device,"
"cl_autopartition_disk_dev)",
'condition': lambda dv: dv.Get('cl_autopartition_set') == 'on'},
# форматирование разделов на которые устанавливается дистрибутив
{'name': 'format',
'message': __("Formatting the partitions"),
'method': 'Install.format(cl_target)',
'condition': lambda dv: dv.Get('cl_target').needFormat},
# распаковка дистрибутива
{'name': 'unpack',
'message': __("Unpacking the system image to the target"),
'method': 'Install.unpack(cl_image,cl_target,os_install_linux_files)',
},
# отметка что установка идет на HDD
{'name': 'hdd',
'condition': lambda dv: dv.Get(
'os_install_root_type') != 'flash' and
dv.Get('os_install_pxe') == 'off'},
# копирование clt шаблонов
{'name': 'hdd:copy_clt',
'message': __("Copying clt templates to the new system"),
'method': 'Install.copyClt(cl_source,cl_target,cl_template_clt_path)'
},
# копирование прочих файлов
{'name': 'hdd:copy_other',
'message': __("Copying other settings to the new system"),
'method': 'Install.copyOther(cl_source,cl_target)',
'condition': lambda dv: dv.Get('os_root_type') != "livecd",
# список задач для дейсвия
tasks = \
[# авторазметка диска
{'name':'autopartition',
'message':__("Creating a new partition table"),
'method':"Install.autopartition(cl_autopartition_table,"
"cl_autopartition_device,cl_autopartition_disk_data,"
"cl_autopartition_lvm_set,cl_autopartition_lvm_vgname,"
"cl_autopartition_bios_grub_set,"
"cl_autopartition_bios_grub_size)",
'condition':lambda dv:dv.Get('cl_autopartition_set') == 'on'},
# форматирование разделов на которые устанавливается дистрибутив
{'name':'format',
'message':__("Formatting the partitions"),
'method':'Install.format(cl_target)',
'condition':lambda dv:dv.Get('cl_target').needFormat},
# распаковка дистрибутива
{'name':'unpack',
'message':__("Unpacking the system image to the target"),
'method':'Install.unpack(cl_image,cl_target,os_install_linux_files)',
},
# отметка что установка идет на HDD
{'name':'hdd',
'condition':lambda dv:dv.Get('os_install_root_type') != 'flash' and \
dv.Get('os_install_pxe') == 'off'},
# копирование clt шаблонов
{'name':'hdd:copy_clt',
'message':__("Copying clt templates to the new system"),
'method':'Install.copyClt(cl_source,cl_target,cl_template_clt_path)'
},
# перемонтирование ntfs для определения windows
{'name': 'hdd:remount_ntfs',
'method': 'Install.remountNTFS()',
'essential': False,
# копирование прочих файлов
{'name':'hdd:copy_other',
'message':__("Copying other settings to the new system"),
'method':'Install.copyOther(cl_source,cl_target)',
'condition':lambda dv:dv.Get('os_root_type') != "livecd",
},
# наложение шаблонов при установке на жесткий диск
{'name': 'hdd:apply_templates',
'message': __("Updating the configuration"),
# наложить шаблоны в установленный дистрибутив, включая clt шаблоны
# без использования фильтров по clt шаблонам
'method': 'Install.applyTemplates(cl_target,True,False,None)',
# перемонтирование ntfs для определения windows
{'name':'hdd:remount_ntfs',
'method':'Install.remountNTFS()',
'essential':False,
},
# наложение шаблонов при PXE установке
{'name': 'apply_templates_pxe',
'message': __("Configuring PXE install"),
# наложить шаблоны в установленный дистрибутив, исключая clt
# без использования фильтров по clt шаблонам
'method': 'Install.applyTemplates(None,False,False,None)',
'condition': lambda dv: dv.Get('os_install_pxe') == 'on'
# наложение шаблонов при установке на жесткий диск
{'name':'hdd:apply_templates',
'message':__("Updating the configuration"),
# наложить шаблоны в установленный дистрибутив, включая clt шаблоны
# без использования фильтров по clt шаблонам
'method':'Install.applyTemplates(cl_target,True,False,None)',
},
# наложение шаблонов при установке на flash диск
{'name': 'apply_templates_flash',
'message': __("Configuring Flash install"),
# наложить шаблоны в установленный дистрибутив, исключая clt
# без использования фильтров по clt шаблонам
'method': 'Install.applyTemplates(None,False,False,cl_target)',
'condition': lambda dv: dv.Get('os_install_root_type') == "flash"
# наложение шаблонов при PXE установке
{'name':'apply_templates_pxe',
'message':__("Configuring PXE install"),
# наложить шаблоны в установленный дистрибутив, исключая clt
# без использования фильтров по clt шаблонам
'method':'Install.applyTemplates(None,False,False,None)',
'condition':lambda dv:dv.Get('os_install_pxe') == 'on'
},
# наложение шаблонов при установке на flash диск
{'name':'apply_templates_flash',
'message':__("Configuring Flash install"),
# наложить шаблоны в установленный дистрибутив, исключая clt
# без использования фильтров по clt шаблонам
'method':'Install.applyTemplates(None,False,False,cl_target)',
'condition':lambda dv:dv.Get('os_install_root_type') == "flash"
},
# подключить точки монтирования bind
{'name':'hdd:mount_bind',
'message':__("Post-install configuration"),
'method':"Install.mountBind(cl_target)",
},
# подключить точки монтирования bind
{'name': 'hdd:mount_bind',
'message': __("Post-install configuration"),
'method': "Install.mountBind(cl_target)",
# перенос пользователей
{'name':'hdd:user_migrate',
'message':__("Migrating users"),
'method':'Install.userMigrate(cl_target,cl_migrate_data,'
'cl_migrate_root_pwd)',
},
# перенос пользователей
{'name': 'hdd:user_migrate',
'message': __("Migrating users"),
'method': 'Install.userMigrate(cl_target,cl_migrate_data,'
'cl_migrate_root_pwd)',
},
# прописывание локальных администраторов
{'name': 'hdd:write_admins',
'method': 'Install.update_admin_ini()',
},
# подготовка загрузчика
{'name': 'prepare_boot',
'message': __("Preparing the system for reboot"),
'method': 'Install.prepareBoot(cl_target)',
'condition': lambda dv: (dv.Get('os_install_mbr') or
dv.Get('os_install_uefi_set') == 'on') and
dv.Get('os_install_pxe') == 'off'},
# отключение исходного дистрибутива
{'name': 'umount_source',
'message': __("Letting go the source distribution"),
'method': 'Install.umount(cl_image)',
'condition': lambda dv: dv.Get('cl_image') and dv.Get(
'cl_image').childs,
'depend': Tasks.has("unpack")},
# отключение установленного дистрибутива
{'name': 'umount_target',
'message': __("Unmounting the target system volume"),
'method': 'Install.umount(cl_target)',
'condition': lambda dv: dv.Get('cl_target') and dv.Get(
'cl_target').childs,
'depend': Tasks.has("unpack")},
# вывести сообщение в случае успеха
{'name': 'success',
'message': __("System successfully installed!")},
# вывести сообщение в случае ошибки
{'name': 'failed',
'message': __("Failed to install the system!"),
'depend': (Tasks.failed() & Tasks.hasnot("interrupt"))},
# вывести сообщение о том, что установка прервана пользователем
{'name': 'intmessage',
'message': __("Installation manually interrupted"),
'depend': Tasks.has("interrupt")},
# подтверждение на перезагрузку
{'name': 'ask_reboot',
'message': __("Would you like to reboot your computer "
# подготовка загрузчика
{'name':'prepare_boot',
'message':__("Preparing the system for reboot"),
'method':'Install.prepareBoot(cl_target)',
'condition':lambda dv:(dv.Get('os_install_mbr') or \
dv.Get('os_install_uefi_set') == 'on') and \
dv.Get('os_install_pxe') == 'off'},
# отключение исходного дистрибутива
{'name':'umount_source',
'message':__("Letting go the source distribution"),
'method':'Install.umount(cl_image)',
'condition':lambda dv:dv.Get('cl_image') and dv.Get('cl_image').childs,
'depend': Tasks.has("unpack")},
# отключение установленного дистрибутива
{'name':'umount_target',
'message':__("Unmounting the target system volume"),
'method':'Install.umount(cl_target)',
'condition':lambda dv:dv.Get('cl_target') and dv.Get('cl_target').childs,
'depend': Tasks.has("unpack")},
# вывести сообщение в случае успеха
{'name':'success',
'message':__("System successfully installed!")},
# вывести сообщение в случае ошибки
{'name':'failed',
'message':__("Failed to install the system!"),
'depend': (Tasks.failed() & Tasks.hasnot("interrupt"))},
# вывести сообщение о том, что установка прервана пользователем
{'name':'intmessage',
'message':__("Installation manually interrupted"),
'depend': Tasks.has("interrupt")},
# подтверждение на перезагрузку
{'name':'ask_reboot',
'message':__("Would you like to reboot your computer "
"now to complete the installation?"),
'confirm': 'no',
'condition': lambda Get: (Get('os_install_pxe') == 'off' and
Get('os_install_root_type') != "flash")
},
# перезагрузить компьютер
{'name': 'reboot',
'message': __("System reboot"),
'command': '/sbin/reboot',
'depend': Tasks.result("ask_reboot", eq='yes')
'confirm':'no',
'condition':lambda dv:dv.Get('os_install_pxe') == 'off'},
# перезагрузить компьютер
{'name':'reboot',
'message':__("System reboot"),
'command':'/sbin/reboot',
'depend':Tasks.result("ask_reboot",eq='yes')
}
]
]

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2010-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2010-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -15,137 +15,105 @@
# limitations under the License.
import sys
from calculate.core.server.func import Action
from ..distr import DistributiveError
from ..migrate_users import MigrationError
from calculate.lib.cl_lang import setLocalTranslate, getLazyLocalTranslate, _
from calculate.lib.cl_template import TemplatesError
from calculate.core.server.func import Action,Tasks
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
from calculate.lib.utils.files import FilesError
from calculate.lib.utils.portage import isPkgInstalled
from ..install import InstallError
from ..variables.autopartition import AutopartitionError
from calculate.install.install import (MigrationError, TemplatesError,
InstallError,
AutopartitionError, DistributiveError)
setLocalTranslate('cl_install3', sys.modules[__name__])
setLocalTranslate('cl_install3',sys.modules[__name__])
__ = getLazyLocalTranslate(_)
class ClSetupVideoAction(Action):
"""
Действие для настройки параметров видео
"""
# ошибки, которые отображаются без подробностей
native_error = (FilesError, MigrationError, TemplatesError,
InstallError, AutopartitionError, DistributiveError)
native_error = (FilesError,MigrationError, TemplatesError,
InstallError, AutopartitionError, DistributiveError)
templateTaskMessage = __("Video settings are being configured")
successMessage = __("Video settings configured!")
failedMessage = __("Failed to configure the video settings!")
interruptMessage = __("Configuration manually interrupted")
prev_tasks = [
addon_tasks = [
# проверить и настроить параметры для nvidia драйвера
{'name': 'drop_xorg_log',
'method': 'Install.drop_xorg_logs()',
'condition': lambda Get: (
Get('os_install_x11_video_drv_prev')
!= Get('os_install_x11_video_drv'))
{'name':'check_video',
'message':__("Checking the video driver"),
'method':'Install.checkVideoDriver()',
'condition': lambda:isPkgInstalled('xorg-server')
},
]
addon_tasks = [
{'name': 'check_video',
'message': __("Checking the video driver"),
'method': 'Install.checkVideoDriver()',
'condition': lambda: isPkgInstalled('xorg-server')
},
{'name': 'setupvideo',
'condition': lambda Get: Get('cl_setup') == 'video'
},
{'name': 'setupvideo:reboot',
'warning': __("To apply the changes, reboot the system"),
'condition': lambda Get: ((Get('os_x11_video_drv') !=
Get('os_install_x11_video_drv') and
(Get('os_x11_video_drv') in Get(
'os_x11_kms_video_drv')
or Get('os_install_x11_video_drv')
in Get('os_x11_kms_video_drv')))
and Get('os_install_root_type') != 'livecd')
},
{'name': 'setupvideo:restart',
'warning': __("To apply the changes, restart the X server"),
'condition': lambda Get: ((Get('os_x11_video_drv') !=
Get('os_install_x11_video_drv') and
(not Get('os_x11_video_drv') in
Get('os_x11_kms_video_drv') and
not Get('os_install_x11_video_drv')
in Get('os_x11_kms_video_drv')))
and Get('os_install_root_type') != 'livecd')
}
]
def __init__(self):
# список задач для действия
self.tasks = self.prev_tasks + [
{'name': 'apply_templates',
'message': self.templateTaskMessage,
# наложить шаблоны на текущий дистрибутив, включая clt шаблоны
# без использования фильтров по clt шаблонам
'method': 'Install.applyTemplates(cl_source,cl_template_clt_set,'
'cl_merge_set,None)',
}]
{'name':'setup_opengl',
'message':__("Configuring OpenGL"),
'method':'Install.setupOpenGL()',
'condition': lambda:isPkgInstalled('xorg-server')
},
{'name':'reboot',
'warning':__("To apply the changes, reboot the system"),
'condition': lambda Get:((Get('os_x11_video_drv') != \
Get('os_install_x11_video_drv') and \
(Get('os_x11_video_drv') in Get('os_x11_kms_video_drv') \
or Get('os_install_x11_video_drv') \
in Get('os_x11_kms_video_drv')))
and Get('os_install_root_type') != 'livecd')
},
{'name':'restart',
'warning':__("To apply the changes, restart the X server"),
'condition': lambda Get:((Get('os_x11_video_drv') !=
Get('os_install_x11_video_drv') and
(not Get('os_x11_video_drv') in
Get('os_x11_kms_video_drv') and
not Get('os_install_x11_video_drv')
in Get('os_x11_kms_video_drv')))
and Get('os_install_root_type') != 'livecd')
}
]
def __init__(self, *vars, **kw):
# список задач для дейсвия
self.tasks = [
{'name':'apply_templates',
'message':self.templateTaskMessage,
# наложить шаблоны на текущий дистрибутив, включая clt шаблоны
# без использования фильтров по clt шаблонам
'method':'Install.applyTemplates(cl_source,cl_template_clt_set,'\
'cl_merge_set,None)',
}]
# выполнить дополнительные задачи
self.tasks.extend(self.addon_tasks)
Action.__init__(self)
Action.__init__(self, *vars, **kw)
class ClSetupSystemAction(ClSetupVideoAction):
"""
Объект настройки всех параметров системы
"""
prev_tasks = []
templateTaskMessage = __("The system is being configured")
successMessage = __("System configured!")
failedMessage = __("Failed to configure the system!")
class ClSetupAudioAction(ClSetupSystemAction):
"""
Действие для настройки аудио параметров
"""
addon_tasks = []
prev_tasks = []
templateTaskMessage = __("The audio settings are being configured")
successMessage = __("Audio settings configured!")
failedMessage = __("Failed to configure the audio parameters!")
class ClSetupThemesAction(ClSetupSystemAction):
"""
Действие для настройки тем
"""
addon_tasks = []
prev_tasks = [
{'name': 'init_themes',
'method': 'Install.init_themes()'
},
]
templateTaskMessage = __("The themes are being configured")
successMessage = __("Themes configured!")
failedMessage = __("Theme configuration failed!")
class ClSetupLocaleAction(ClSetupSystemAction):
"""
Действие для настройки языковых параметров
"""
addon_tasks = []
prev_tasks = []
templateTaskMessage = \
__("The localization and time options are being configured")
successMessage = __("System configured!")
failedMessage = __("Failed to configure the system!")
class ClSetupNetworkAction(ClSetupSystemAction):
"""
Действие для настройки аудио параметров
@ -155,7 +123,6 @@ class ClSetupNetworkAction(ClSetupSystemAction):
successMessage = __("Network settings configured!")
failedMessage = __("Failed to configure the network settings!")
class ClSetupSessionAction(ClSetupSystemAction):
"""
Действие для настройки пользовательских параметров
@ -165,7 +132,6 @@ class ClSetupSessionAction(ClSetupSystemAction):
successMessage = __("Session settings configured!")
failedMessage = __("Failed to configure the session settings!")
class ClSetupBootAction(ClSetupSystemAction):
"""
Действие для настройки параметров загрузки
@ -174,19 +140,27 @@ class ClSetupBootAction(ClSetupSystemAction):
successMessage = __("Boot parameters configured!")
failedMessage = __("Failed to configure the boot parameters!")
prev_tasks = []
addon_tasks = [
# установить загрузчик
{'name': 'prepare_bootloader',
'message': _("Installing the bootloader"),
'method': 'Install.prepareBoot(cl_image)',
'condition': (lambda Get: (Get('os_install_mbr') or
Get('os_install_uefi_set') == 'on') and
Get('os_root_type') != 'livecd' and
Get('os_install_scratch') == 'off')
},
{'name': 'no_scratch',
'warning': _("The builder mode is no longer supported"),
'condition': lambda Get: Get('os_install_scratch') == 'on'
},
]
{'name':'prepare_bootloader',
'message':_("Installing the bootloader"),
'method':'Install.prepareBoot(cl_image)',
'condition':(lambda Get:(Get('os_install_mbr') or
Get('os_install_uefi_set') == 'on') and
Get('os_root_type') != 'livecd' and
Get('os_install_scratch') == 'off')
},
{'name':'no_scratch',
'warning':_("The builder mode is no longer supported"),
'condition':lambda Get:Get('os_install_scratch') == 'on'
},
# изменить IO планировщик
{'name':'change_ioscheduler',
'message':_("Changing the I/O scheduler"),
'method':'Install.changeScheduler(os_install_kernel_scheduler)',
'condition':(lambda dv:dv.Get('os_root_type') != 'livecd' and
dv.Select('os_disk_parent',
where='os_disk_mount',
eq='/',limit=1))
},
]

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -18,31 +18,20 @@ import os
import sys
import re
from os import path
import hashlib
import glob
from calculate.lib.datavars import Variable, VariableError, ReadonlyVariable
from calculate.lib.utils.portage import isPkgInstalled
from calculate.lib.utils.files import readFile, readFileEx
from calculate.lib.utils.tools import get_best_nearest_resolution
import calculate.lib.utils.device as device
from calculate.lib.utils.files import process, STDOUT, getProgPath, readFile
from calculate.lib.utils.common import (getVideoFromXorgLog,
getVideoFromXorgConf,
getVideoFromCmdLine,
getAvailableVideo, getValueFromCmdLine,
getCompositeFromXorgconf,
getVideoFromModules,
getVideoFromVendor, getInstalledVideo,
CmdlineParams)
from calculate.lib.utils.video import get_edid_data, EdidInfoError, EdidInfo
from ..distr import DistributiveError
getVideoFromXorgConf, getVideoFromCmdLine,
getAvailableVideo, getValueFromCmdLine,
getCompositeFromXorgconf, getVideoFromModules,
getVideoFromVendor, getInstalledVideo)
from calculate.install.distr import DistributiveError
import fcntl
import struct
from collections import OrderedDict
from calculate.lib.cl_lang import setLocalTranslate, _
setLocalTranslate('cl_install3', sys.modules[__name__])
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
class VideoVariable(Variable):
"""
@ -50,16 +39,13 @@ class VideoVariable(Variable):
"""
xorg_need = True
default_video = "default"
driver_names = OrderedDict([
('default', _("Auto detection")),
('radeon', _("AMD Radeon (radeon)")),
('amdgpu', _("AMD AMDGPU (amdgpu)")),
('modesetting', _("Framebuffer device (modesetting)")),
('vesa', _("Generic VESA (vesa)")),
('intel', _("Intel (intel)")),
('nouveau', _("Nvidia Nouveau (nouveau)")),
('nvidia', _("Nvidia Graphics Driver (nvidia)")),
])
driver_names = {'nvidia': _("NVidia proprietary video driver"),
'fglrx': _("ATI proprietary video driver"),
'intel': _("Intel video driver"),
'radeon': _("ATI open source video driver"),
'nouveau': _("NVidia open source video driver"),
'default': _("X.Org Server auto detection")
}
def uncompatible(self):
"""
@ -68,19 +54,16 @@ class VideoVariable(Variable):
if self.Get('os_install_root_type') == 'flash':
return \
_("Video configuration unavailable for Flash install")
if (self.Get('install.os_install_x11_server_set') == 'off' and
self.xorg_need):
if self.Get('os_install_x11_server_set') == 'off' and self.xorg_need:
return \
_("This distribution does not provide a Xorg server")
return ""
class ResolutionVariable(VideoVariable):
"""
Abstract resolution variable
"""
fbres = False
def choice(self):
resolutions = ["640x480", "800x480", "800x600", "1024x576", "1024x600",
"1024x768", "1200x800", "1280x800", "1280x720",
@ -90,31 +73,28 @@ class ResolutionVariable(VideoVariable):
"1600x900", "1600x1200", "2048x1152", "2560x1440",
"2560x1600"]
if self.fbres:
return ["%s-32" % x for x in resolutions]
return map(lambda x:"%s-32"%x,
resolutions)
else:
return resolutions
def check(self, value):
def check(self,value):
"""
Check resolution format 1234x567
"""
if not re.match('^\d+x\d+(-\d+(@\d+)?)?$', value):
if not re.match('^\d+x\d+(-\d+(@\d+)?)?$',value):
raise VariableError(
_("Wrong resolution {resolution} {example}").format(
resolution=value,
example="(%s:%s)" % (_("Example"), "1024x768")))
resolution=value,
example="(%s:%s)"%(_("Example"),"1024x768")))
class VariableOsInstallX11ResolutionPreferred(ResolutionVariable):
class VariableOsInstallX11Resolution(ResolutionVariable):
"""
X.org resolution
"""
type = 'choiceedit'
opt = ['-X']
metavalue = "<width>x<height>"
# разрешение по умолчанию пустое - это нужно для livecd
# для автоопределения разрешения xorg сервером
preferred_resolution = ""
def init(self):
self.help = _("set the Xorg resolution")
@ -123,64 +103,34 @@ class VariableOsInstallX11ResolutionPreferred(ResolutionVariable):
def get(self):
# get resolution from xorg.log
res = self.Get('os_x11_resolution')
if res:
if res or self.Get('os_install_root_type') in ('livecd','usb-hdd'):
return res
else:
return self.preferred_resolution
class VariableOsInstallX11Resolution(ResolutionVariable):
"""
X.org resolution
"""
fallback_resolution = "1024x768"
FBIOGET_VSCREENINFO = 0x4600
def framebuffer_resolution(self):
try:
fbdev = os.open('/dev/fb0', os.O_RDONLY)
data = fcntl.ioctl(fbdev, self.FBIOGET_VSCREENINFO, " " * 8)
res = struct.unpack("II", data)
return "%sx%s" % (res[0], res[1])
except (IOError, OSError):
pass
return ""
def get(self):
# get resolution from xorg.log
res = self.Get('install.os_install_x11_resolution_preferred')
if res:
return res
res = self.framebuffer_resolution()
if res:
return res
return self.fallback_resolution
return self.choice()[-1]
class VariableOsInstallX11VideoAvailable(VideoVariable):
"""
Get available (already installed or installable drivers
"""
type = "list"
# supported = ["nvidia", "fglrx", "amdgpu", "nouveau", "intel", "radeon"]
supported = ["nvidia", "amdgpu","modesetting",
"nouveau", "intel", "radeon", "vesa"]
supported = ["nvidia", "fglrx", "nouveau", "intel", "radeon"]
def get(self):
image = self.Get('cl_image')
if image:
with image:
with image as distr:
try:
distrPath = image.getDirectory()
if isPkgInstalled('xorg-server', prefix=distrPath):
if isPkgInstalled('xorg-server',prefix=distrPath):
return (sorted(filter(self.supported.__contains__,
getAvailableVideo(
prefix=distrPath))) +
getAvailableVideo(prefix=distrPath))) +
[self.default_video])
except DistributiveError:
except DistributiveError as e:
pass
return []
def humanReadable(self):
return [self.driver_names.get(x, x) for x in self.Get()]
return map(lambda x: self.driver_names.get(x, x), self.Get())
class VariableOsX11KmsVideoDrv(ReadonlyVariable):
@ -188,7 +138,7 @@ class VariableOsX11KmsVideoDrv(ReadonlyVariable):
Список KMS драйверов
"""
type = "list"
value = ["radeon", "intel", "nouveau", "amdgpu", "modesetting"]
value = ["radeon", "intel", "nouveau"]
class VariableOsInstallX11VideoDrv(VideoVariable):
@ -203,22 +153,13 @@ class VariableOsInstallX11VideoDrv(VideoVariable):
self.help = _("set the video driver")
self.label = _("Video driver")
def nox_video_drivers(self):
values = self.Get('os_x11_kms_video_drv')
for drv, drvinfo in self.pkgDrvMap.items():
_, pkgdrv = drvinfo
if isPkgInstalled(pkgdrv, prefix=self.Get('cl_chroot_path')):
values.append(drv)
return [self.default_video] + list(sorted(values))
def choice(self):
"""Get available (already installed or installable drivers"""
if self.Get('os_install_x11_server_set') == 'on':
values = self.Get('os_install_x11_video_available')
else:
values = self.nox_video_drivers()
return [(x, self.driver_names.get(x, x)) for x
in [y for y in self.driver_names.keys() if y in values]]
values = self.Get('os_x11_kms_video_drv') + [self.default_video]
return map(lambda x: (x, self.driver_names.get(x, x)), values)
def get(self):
if self.Get('os_install_x11_server_set') == 'on':
@ -228,54 +169,52 @@ class VariableOsInstallX11VideoDrv(VideoVariable):
return self.default_video
# if type system is usb-hdd then get detect video driver
if self.Get('os_install_root_type') == 'usb-hdd':
methods = ((getVideoFromModules, ()),
(getVideoFromCmdLine, ()),
(getVideoFromVendor,
(self.Get('hr_video'), list_video)))
methods = ((getVideoFromModules,()),
(getVideoFromCmdLine,()),
(getVideoFromVendor,(self.Get('hr_video'),list_video)))
else:
# test current video driver for install system
methods = ((getVideoFromXorgLog, ('/', list_video)),
(getVideoFromXorgConf, ('/',)),
(getVideoFromCmdLine, ()),
(getVideoFromModules, ()),
(getVideoFromVendor,
(self.Get('hr_video'), list_video)))
for func, args in methods:
methods = ((getVideoFromXorgLog,('/',list_video)),
(getVideoFromXorgConf,('/',)),
(getVideoFromModules,()),
(getVideoFromCmdLine,()),
(getVideoFromVendor,(self.Get('hr_video'),list_video)))
for func,args in methods:
drv = func(*args)
if drv in list_video:
return drv
return self.default_video
else:
for drv in (x[0] for x in self.choice()):
refcnt = device.sysfs.read(
device.sysfs.Path.Module, drv, "refcnt").strip()
for drv in map(lambda x:x[0], self.choice()):
videoSysPath = path.join("/sys/module",drv,"refcnt")
refcnt = readFile(videoSysPath).strip()
if refcnt.isdigit() and int(refcnt) > 0:
return {'i915': 'intel'}.get(drv, drv)
return {'i915':'intel'}.get(drv,drv)
else:
return self.default_video
pkgDrvMap = {'nvidia': ('NVidia', 'x11-drivers/nvidia-drivers'),
'fglrx': ('ATI', 'x11-drivers/ati-drivers'),
'vboxdrv': ('VirtualBox', 'x11-drivers/xf86-video-virtualbox')}
pkgDrvMap = {'nvidia':('NVidia','x11-drivers/nvidia-drivers'),
'fglrx':('ATI','x11-drivers/ati-drivers'),
'vboxdrv':('VirtualBox','x11-drivers/xf86-video-virtualbox')}
def check(self, value):
def check(self,value):
if self.Get('os_install_x11_server_set') == 'on':
if self.Get('cl_action') == 'system':
availDrvs = self.Get('os_install_x11_video_available')
if not value in availDrvs:
raise VariableError(_("Only %s drivers are available") %
",".join(availDrvs))
raise VariableError(_("Only %s drivers are available")%
",".join(availDrvs))
else:
if not value in getInstalledVideo(prefix="/") and \
not value in ("auto", self.default_video):
error = _("video driver %s is unavailable") % value
not value in ("auto",self.default_video):
error =_("video driver %s is unavailable")%value
if value in self.pkgDrvMap:
error += ". " + (_("Install driver %s with:")
% self.pkgDrvMap[value][0])
error += "\n" + ("emerge %s" % self.pkgDrvMap[value][1])
%self.pkgDrvMap[value][0])
error += "\n" + ("emerge %s"%self.pkgDrvMap[value][1])
raise VariableError(error)
else:
availDrivers = self.nox_video_drivers()
availDrivers = self.Get('os_x11_kms_video_drv') + [self.default_video]
if not value in availDrivers:
raise VariableError("Only %s drivers are available" %
",".join(availDrivers))
@ -289,13 +228,6 @@ class VariableOsInstallX11VideoDrv(VideoVariable):
_("Video configuration unavailable for Flash install")
return ""
class VariableOsInstallX11VideoDrvPrev(VariableOsInstallX11VideoDrv):
"""
Предыдущее значение os_install_x11_videodrv
"""
class VariableHrVideoId(ReadonlyVariable):
"""
BusID of video card
@ -303,7 +235,6 @@ class VariableHrVideoId(ReadonlyVariable):
"""
value = ""
class VariableOsInstallX11Composite(VideoVariable):
"""
on/off composite
@ -317,18 +248,14 @@ class VariableOsInstallX11Composite(VideoVariable):
def get(self):
"""On/off composite"""
defaultCompositeOn = ("nvidia", "intel", "fglrx", "amdgpu",
"modesetting",
"nouveau", "radeon", "default")
composite = getValueFromCmdLine(CmdlineParams.Calculate,
CmdlineParams.Composite)
videodrv = getValueFromCmdLine(CmdlineParams.Calculate,
CmdlineParams.Video)
defaultCompositeOn = ("nvidia","intel","fglrx","nouveau","radeon")
composite = getValueFromCmdLine("calculate",5)
videodrv = getValueFromCmdLine("calculate",4)
if videodrv != "auto":
composite = {'nocomposite': 'off',
'off': 'off',
'on': 'on',
'composite': 'on'}.get(composite)
composite = {'nocomposite':'off',
'off':'off',
'on':'on',
'composite':'on'}.get(composite)
else:
composite = None
@ -344,31 +271,6 @@ class VariableOsInstallX11Composite(VideoVariable):
state = None
return composite or state or defaultComposite
class VariableOsInstallFbResolutionPreferred(ResolutionVariable):
"""
Framebuffer resolution
"""
type = 'choiceedit'
opt = ['--fb']
metavalue = "<width>x<height>"
xorg_need = False
fbres = True
value = "auto"
def init(self):
self.help = _("set the framebuffer resolution")
self.label = _("Framebuffer resolution")
def choice(self):
yield ("auto", _("Auto"))
for i in ResolutionVariable.choice(self):
yield (i,i)
def check(self, value):
if value == "auto":
return
ResolutionVariable.check(self, value)
class VariableOsInstallFbResolution(ResolutionVariable):
"""
Framebuffer resolution
@ -378,174 +280,20 @@ class VariableOsInstallFbResolution(ResolutionVariable):
metavalue = "<width>x<height>"
xorg_need = False
fbres = True
fallback_resolution = "1024x768"
def init(self):
self.help = _("set the framebuffer resolution")
self.label = _("Framebuffer resolution")
def using_kms(self):
drv = self.Get('install.os_install_x11_video_drv')
kms = self.Get('install.os_x11_kms_video_drv')
return drv in kms
def using_uefi(self):
return self.GetBool('install.os_install_uefi_set')
def get(self):
custom = self.Get('os_install_fb_resolution_preferred')
if custom != "auto":
return custom
x11res = self.Get('os_install_x11_resolution')
if self.using_kms() or self.using_uefi():
return x11res
hwinfo = device.Hwinfo()
try:
return get_best_nearest_resolution(
x11res, hwinfo.resolutions()) or self.fallback_resolution
except (ZeroDivisionError, device.HwinfoError):
return self.fallback_resolution
class VariableClGrubImageHash(ReadonlyVariable):
"""
Контрольная сумма изображения для grub
"""
grub_image = "/boot/grub/grub-calculate.png"
theme_data = "/etc/grub.d/05_theme"
def get_image_md5(self, source):
return hashlib.md5(readFile(source, binary=True)).hexdigest()
def get_config_md5(selfself, source):
return hashlib.md5(readFileEx(source, grab=True)).hexdigest()
def get_checksum(self):
data = []
if path.exists(self.grub_image):
data.append(self.get_image_md5(self.grub_image))
else:
data.append("-")
if path.exists(self.theme_data):
data.append(self.get_config_md5(self.theme_data))
else:
data.append("-")
return "".join(data)
def get(self):
if self.Get('cl_setup') == 'themes':
return self.get_checksum()
return ""
class VariableClGrubImageUpdateSet(VariableClGrubImageHash):
"""
Изображение для grub обновлилось
"""
def get(self):
if self.Get('cl_setup') == 'themes':
newmd5 = self.get_checksum()
return "on" if newmd5 != self.Get('cl_grub_image_hash') else "off"
return "off"
class VariableClSplashImageHash(ReadonlyVariable):
"""
Контрольные суммы изображений для splashutils
"""
hash_files = ("/etc/splash/calculate/images/verbose.md5",
"/etc/splash/calculate/images/silent.md5",
"/usr/share/plymouth/themes/calculate/boot.md5",
"/usr/share/plymouth/themes/calculate/boot/md5sum",
"/usr/share/plymouth/themes/calculate/calculate.plymouth")
cfg_files = "/etc/splash/calculate/*.cfg"
def get_config_md5(selfself, source):
return hashlib.md5(readFileEx(source, grab=True)).hexdigest()
def get_hash_data(self, sources):
data = []
for fn in sources:
data.append(self.get_config_md5(fn))
for fn in glob.glob(self.cfg_files):
data.append(self.get_config_md5(fn))
break
return "".join(data)
def get(self):
if self.Get('cl_setup') == 'themes':
return self.get_hash_data(self.hash_files)
return ""
class VariableClSplashImageUpdateSet(VariableClSplashImageHash):
"""
Изображение для splash dracut обновлилось
"""
def get(self):
if self.Get('cl_setup') == 'themes':
newmd5 = self.get_hash_data(self.hash_files)
return "on" if newmd5 != self.Get('cl_splash_image_hash') else "off"
return "off"
class VariableClInstallEdidData(ReadonlyVariable):
type = Variable.Types.Object
def get(self):
edid_data = get_edid_data()
if not edid_data:
return {}
try:
ei = EdidInfo()
ei.set_data(edid_data)
return {
"resolution": ei.resolution,
"ratio": ei.ratio,
"screensize": ei.screensize
}
except EdidInfoError as e:
return {}
class VariableClInstallEdidResolution(ReadonlyVariable):
def get(self):
return self.Get('cl_install_edid_data').get('resolution','')
class VariableClInstallEdidScreensize(ReadonlyVariable):
def get(self):
return self.Get('cl_install_edid_data').get('screensize','')
class VariableClInstallCalculateDpi(Variable):
def get(self):
inch = 25.4
screensize = self.Get('cl_install_edid_screensize')
resolution = self.Get('os_install_x11_resolution')
if screensize and resolution:
cx = screensize.partition("x")[0]
cxres = resolution.partition("x")[0]
if cx.isdigit() and cxres.isdigit():
cx = float(cx)
cxres = float(cxres)
return str(int(inch * cxres / cx))
return ""
class VariableClInstallDpi(Variable):
def get(self):
calculate_dpi = self.Get('cl_install_calculate_dpi')
try:
if calculate_dpi:
calculate_dpi = int(calculate_dpi)
if calculate_dpi > 100:
return "108"
except ValueError:
pass
return "96"
FBIOGET_VSCREENINFO = 0x4600
class VariableClInstallScaling(Variable):
def get(self):
dpi = self.Get('cl_install_dpi')
"""Get current framebuffer resolution"""
try:
if dpi:
dpi = int(dpi)
if dpi > 100:
return "hi"
except ValueError:
fbdev = os.open('/dev/fb0',os.O_RDONLY)
data = fcntl.ioctl(fbdev, self.FBIOGET_VSCREENINFO, " "*8)
res = struct.unpack("II",data)
return "%sx%s"%(res[0],res[1])
except (IOError,OSError):
pass
return "normal"
return "1024x768"

@ -1,6 +1,6 @@
#-*- coding: utf-8 -*-
# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -14,17 +14,17 @@
# See the License for the specific language governing permissions and
# limitations under the License.
from . import action
from . import disk
from . import locale
from . import linux
from . import distr
from . import kernel
from . import net
from . import system
from . import X11
from . import lvm
from . import autopartition
from . import audio
import action
import disk
import locale
import linux
import distr
import kernel
import net
import system
import X11
import lvm
import autopartition
import audio
section = "install"

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -14,33 +14,30 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
from calculate.lib.datavars import ActionVariable
from os import path
from calculate.lib.datavars import (Variable,VariableError,ReadonlyVariable,
ActionVariable)
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3', sys.modules[__name__])
ServerSetup = "server_setup"
setLocalTranslate('cl_install3',sys.modules[__name__])
class VariableAcInstallMerge(ActionVariable):
"""
Action variable which has value "on"
in ebuild phase preinst or reconfigure system
"""
def action(self, cl_action):
if (cl_action in ("system", "merge") and
self.Get('os_install_root_type') != 'flash' and
self.Get('os_install_pxe') == 'off' and
self.Get('cl_live') == 'off' or
cl_action in (ServerSetup, "sync",
"domain", "undomain",)
and self.Get('cl_merge_pkg')):
def action(self,cl_action):
if cl_action in ("system","merge") and \
self.Get('os_install_root_type') != 'flash' and \
self.Get('os_install_pxe') == 'off' and \
self.Get('cl_live') == 'off' or \
cl_action in ("sync","domain","undomain") \
and self.Get('cl_merge_pkg'):
return "on"
return "off"
class VariableAcInstallLive(ActionVariable):
"""
Action variable which has value "on"
@ -49,96 +46,72 @@ class VariableAcInstallLive(ActionVariable):
"""
nonchroot = True
def action(self, cl_action):
if (cl_action in ("system", "merge") and
self.Get('os_install_root_type') != 'flash' and
self.Get('os_install_pxe') == 'off' or
cl_action in (ServerSetup,
"sync", "domain", "undomain",)
and self.Get('cl_merge_pkg')):
def action(self,cl_action):
if cl_action in ("system","merge") and \
self.Get('os_install_root_type') != 'flash' and \
self.Get('os_install_pxe') == 'off' or \
cl_action in ("sync","domain","undomain") \
and self.Get('cl_merge_pkg'):
return "on"
return "off"
class VariableAcInstallConfig(ActionVariable):
"""
Action variable which has value "on" for emerge --config
cl-config
"""
def action(self, cl_action):
if cl_action in ("config",):
return "on"
return "off"
class VariableAcInstallDisk(ActionVariable):
"""
Action variable which has value "on" for installation on hdd
"""
def action(self, cl_action):
if (cl_action == 'system' and
self.Get('os_install_root_type') != "flash" and
self.Get('os_install_pxe') != "on"):
def action(self,cl_action):
if cl_action == 'system' and \
self.Get('os_install_root_type') != "flash" and \
self.Get('os_install_pxe') != "on":
return "on"
else:
return "off"
class VariableAcInstallFlash(ActionVariable):
"""
Action variable which has value "on" for USB flash
"""
def action(self, cl_action):
if (cl_action == 'system' and
self.Get('os_install_root_type') == 'flash'):
def action(self,cl_action):
if cl_action == 'system' \
and self.Get('os_install_root_type') == 'flash':
return "on"
return "off"
class VariableAcInstallPxe(ActionVariable):
"""
Action variable which has value "on" for PXE installation
"""
def action(self, cl_action):
def action(self,cl_action):
if cl_action == 'system' and self.Get('os_install_pxe') == 'on':
return "on"
return "off"
class VariableAcInstallConfigure(ActionVariable):
"""
Action variable which has value "up" for configuration
"""
def action(self, cl_action):
cl_setup = self.Get('cl_setup')
if cl_action == "merge" and cl_setup:
def action(self,cl_action):
clSetup = self.Get('cl_setup')
if cl_action == "merge" and clSetup:
return "on"
return "off"
class VariableAcInstallUnmerge(ActionVariable):
"""
Action variable which has value "up" on prerm ebuild phase
"""
def action(self, cl_action):
if (cl_action == "merge" and
self.Get('cl_ebuild_phase') in ('prerm', 'postrm')):
def action(self,cl_action):
if cl_action == "merge" and \
self.Get('cl_ebuild_phase') in ('prerm','postrm'):
return "on"
return "off"
class VariableAcInstallPatch(ActionVariable):
"""
Action variable which has value "on"
in ebuild phase preinst or reconfigure system
"""
def action(self, cl_action):
def action(self,cl_action):
if cl_action in ("patch",):
return "on"
return "off"

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -14,98 +14,16 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import re
from calculate.lib.datavars import (Variable, ReadonlyVariable,
ReadonlyTableVariable, FieldValue,
HumanReadable)
from calculate.lib.utils.common import getValueFromCmdLine, CmdlineParams
from calculate.lib.utils.portage import isPkgInstalled
from calculate.lib.utils.files import readFile, readLinesFile
from ..distr import DistributiveError
import glob
from calculate.lib.cl_lang import setLocalTranslate, _
setLocalTranslate('cl_install3', sys.modules[__name__])
class VariableOsAudio(Variable):
"""
Выбранная аудиосистема
"""
type = "choice"
opt = ['--audio']
metavalue = "AUDIO"
def init(self):
self.label = _("Audio system")
self.help = _("set the audio system")
def get(self):
"""
pipewire по умолчанию если доступно или вписано в /etc/asound.conf
"""
avail = [x[0] for x in self.Get('os_audio_available')]
if "pipewire" in avail:
audio = getValueFromCmdLine(CmdlineParams.Calculate,
CmdlineParams.Audio)
if audio and audio == "alsa":
return "alsa"
else:
return "pipewire"
return "alsa"
def choice(self):
return self.Get('os_audio_available')
def uncompatible(self):
"""
Audio setting up unavailable for flash installation
"""
if self.Get('os_install_root_type') == 'flash':
return _("Audio configuration unavailable for Flash install")
if self.Get('os_install_alsa_set') == 'off':
return _("This distribution does not provide the ALSA sound")
return ""
class VariableOsAudioAvailable(Variable):
"""
Доступные звуковые системы
"""
type = "list"
def get(self):
mapAudioConf = (
('alsa', None, _('ALSA')),
('pipewire', 'media-video/pipewire', _("PipeWire")),
)
image = self.Get('cl_image')
if image:
with image as distr:
try:
distrPath = image.getDirectory()
return [x[0::2] for x
in mapAudioConf
if not x[1] or isPkgInstalled(x[1], prefix=distrPath)]
except DistributiveError as e:
pass
return sorted((x[0::2] for x in mapAudioConf[-1:]), key=lambda x: x[1])
class VariableOsAudioCardMap(ReadonlyVariable):
"""
Соответствие номеров звуковых карт именам
"""
type = Variable.Types.Table
def get(self):
return [(cardid[17:-3], readFile(cardid).strip())
for cardid in glob.glob('/proc/asound/card[0-9]*/id')]
from os import path
from calculate.lib.datavars import (Variable, VariableError, ReadonlyVariable,
ReadonlyTableVariable, FieldValue)
from calculate.lib.utils.files import (readFile, getProgPath, process)
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
class VariableOsAudioData(ReadonlyTableVariable):
"""
@ -114,35 +32,17 @@ class VariableOsAudioData(ReadonlyTableVariable):
source = ['os_audio_id',
'os_audio_name']
def generate_cards(self, cards):
for card_id, card_name in cards:
for playback_info in glob.glob(
"/proc/asound/card%s/pcm[0-9]p/info" % card_id):
dInfo = (x.partition(":")[::2]
for x in readLinesFile(playback_info))
dInfo = {x.strip(): y.strip() for x, y in dInfo}
if all(x in dInfo for x in ('card', 'device', 'name')):
if card_name == dInfo['name']:
yield ("%s,%s" % (dInfo['card'], dInfo['device']),
"%s" % card_name)
else:
yield ("%s,%s" % (dInfo['card'], dInfo['device']),
"%s, %s" % (card_name, dInfo['name']))
def get(self, hr=HumanReadable.No):
# /proc/asound/card*/pcm*p/info
def get(self,hr=False):
data = readFile('/proc/asound/cards')
cards = re.findall('^\s*(\d+).*\s-\s(.+)\n\s+\S.* at .*$',
data, re.M)
cards = re.findall('^\s*(\d+).*\n\s+(\S.*) at .*$',data,re.M)
if cards:
return list(self.generate_cards(cards))
return map(list, cards)
else:
return [[]]
setValue = Variable.setValue
class VariableOsAudioId(FieldValue, ReadonlyVariable):
class VariableOsAudioId(FieldValue,ReadonlyVariable):
"""
Order Id of audio card
"""
@ -150,8 +50,7 @@ class VariableOsAudioId(FieldValue, ReadonlyVariable):
source_variable = "os_audio_data"
column = 0
class VariableOsAudioName(FieldValue, ReadonlyVariable):
class VariableOsAudioName(FieldValue,ReadonlyVariable):
"""
Name of audio card
"""
@ -159,109 +58,55 @@ class VariableOsAudioName(FieldValue, ReadonlyVariable):
source_variable = "os_audio_data"
column = 1
class VariableOsAudioCardDefault(Variable):
class VariableOsAudioDefaultSet(ReadonlyVariable):
"""
Идентификатор карты по умолчанию
Force write in config 0
"""
def get(self):
audio_default = self.Get('os_audio_default')
if audio_default and audio_default != "none":
cardmap = dict(self.Get("os_audio_card_map"))
cardnum = audio_default.split(',')[0]
if cardnum in cardmap:
return cardmap[cardnum]
return "0"
return ""
type = "bool"
class VariableOsAudioDeviceDefault(Variable):
"""
Номер устройства по умолчанию
"""
def get(self):
audio_default = self.Get('os_audio_default')
if audio_default and audio_default != "none":
return self.Get('os_audio_default').split(',')[1]
return ""
res = self.Select('os_audio_id',where='os_audio_name',
notlike='HDMI',limit=1)
audioDefault = self.Get('os_audio_default')
if audioDefault != '0' or \
res and res != "0" and audioDefault == '0' or \
audioDefault != self.Get('os_audio_current'):
return 'on'
return 'off'
class VariableOsAudioCardNameDefault(Variable):
"""
Название карты используемое в настройках KDE
"""
def get(self):
try:
audio_default = self.Get('os_audio_default')
if audio_default and audio_default != "none":
cardnum = int(audio_default.split(',')[0])
audionames = self.Get('os_audio_name')
if cardnum < len(audionames):
return audionames[cardnum].split(',')[0]
except ValueError:
pass
return ""
class VariableOsAudioHw(Variable):
class VariableOsAudioCurrent(ReadonlyVariable):
"""
Current default audio card
"""
def get_deprecated(self):
asound_data = readFile('/etc/asound.conf')
default_card_re = re.compile('defaults.ctl.card\s+(\d+)')
entry = default_card_re.search(asound_data)
if entry and entry.groups()[0] in self.Get('os_audio_id'):
return "%s,0" % entry.groups()[0]
default_card_re = re.compile(
'pcm.!default {[^}]+card\s+(\d+)[^}]+device\s+(\d+)[^}]+}')
entry = default_card_re.search(asound_data)
if entry:
entry = "%s,%s" % entry.groups()
if entry in self.Get('os_audio_id'):
return entry
return ""
def get(self):
cardmap = dict(self.Get("os_audio_card_map"))
value = self.get_deprecated()
if not value:
value = self.Select('os_audio_id', where='os_audio_name',
notlike='HDMI', limit=1) or "0,0"
cardnum, devicenum = value.split(",")
if cardnum in cardmap:
return "{},{}".format(cardmap[cardnum], devicenum)
return ""
defaultCardRe = re.compile('defaults.ctl.card\s+(\d+)')
entry = defaultCardRe.search(readFile('/etc/asound.conf'))
if entry and entry.groups()[0] in self.Get('os_audio_id'):
return entry.groups()[0]
res = self.Select('os_audio_id',where='os_audio_name',
notlike='HDMI',limit=1)
return res or '0'
class VariableOsAudioDefault(Variable):
"""
Current default audio card
"""
type = "choice"
opt = ['--card']
metavalue = "CARD"
type = "choice"
opt = ['--audio']
def init(self):
self.label = _("Default audio card")
self.help = _("set the default audio")
def get(self):
current = self.Get('os_audio_hw')
if current and "," in current:
cardmap = {y:x for x, y in self.Get("os_audio_card_map")}
cardid, devicenum = current.split(",")
if cardid in cardmap:
return "{},{}".format(cardmap[cardid], devicenum)
data = self.Get('os_audio_data')
if data and data[0]:
return "0,0"
return "none"
return self.Get('os_audio_current')
def choice(self):
data = self.Get('os_audio_data')
if data and data[0]:
return self.Get('os_audio_data')
return [("none", _("Not available"))]
return []
def uncompatible(self):
"""
@ -270,5 +115,6 @@ class VariableOsAudioDefault(Variable):
if self.Get('os_install_root_type') == 'flash':
return _("Audio configuration unavailable for Flash install")
if self.Get('os_install_alsa_set') == 'off':
return _("This distribution does not provide the ALSA sound")
return \
_("This distribution does not provide the ALSA sound")
return ""

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -20,48 +20,39 @@ from os import path
import re
import operator
from operator import itemgetter
from calculate.lib.datavars import (Variable, VariableError, ReadonlyVariable,
CommonVariableError, BuildAlreadyInstalledError)
from calculate.lib.utils.common import (getSupportArch, getTupleVersion,
cmpVersion, cmp)
from calculate.lib.utils.files import listDirectory, pathJoin
from calculate.lib.utils.grub import GrubCommand
from calculate.lib.datavars import Variable,VariableError,ReadonlyVariable, \
CommonVariableError
from calculate.lib.utils.common import getSupportArch,getTupleVersion, \
cmpVersion
from calculate.lib.utils.files import readLinesFile, listDirectory
from calculate.lib.variables.linux import Linux
from ..distr import (Distributive, PartitionDistributive,
DirectoryDistributive, DefaultMountPath,
DistributiveError, FlashDistributive,
ArchiveDistributive,
MultiPartitions, PxeDistributive)
from calculate.lib.cl_lang import setLocalTranslate, _
from ..fs_manager import FileSystemManager
from functools import reduce, cmp_to_key
setLocalTranslate('cl_install3', sys.modules[__name__])
from calculate.install.distr import (Distributive,PartitionDistributive,
DirectoryDistributive,
ScratchPartitionDistributive,DistributiveError,FlashDistributive,
MultiPartitions,PxeDistributive)
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
class DistroRepository(Linux):
contentCache = {}
marches = ['x86_64']
marches = ['i686','x86_64']
extensiton = ['iso', 'tar.bz2', 'tar.gz', 'tar.7z', 'tar.lzma']
extensiton = ['iso','tar.bz2','tar.gz','tar.7z','tar.lzma']
reDistName = re.compile("""
^.*/(?P<os_linux_shortname>%(name)s)
-(?P<os_linux_ver>%(ver)s)
(?:-(?P<serial_id>%(ser)s))?
-(?P<os_arch_machine>%(march)s)
.(?P<ext>%(ext)s)$""" %
{'name': "[a-z0-9]+",
'ver': r"(\d+\.)*\d+",
'ser': r"\d+",
'march': "|".join(marches),
'ext': "|".join(extensiton)
}, re.X)
def _getDistrInfo(self, filename):
{'name':"[a-z0-9]+",
'ver':r"(\d+\.)*\d+",
'march':"|".join(marches),
'ext':"|".join(extensiton)
}, re.X)
def _getDistrInfo(self,filename):
"""Get information by distributive"""
# if filename is directory
if not path.isfile(filename):
@ -78,8 +69,8 @@ class DistroRepository(Linux):
distdic["os_linux_ver"] = ""
return distdic
def getImage(self, scratch, rootType, imagePath, march=None,
shortName=None, linuxVer=None, linuxBuild=None):
def getImage(self,scratch,rootType,imagePath,march=None,
shortName=None,linuxVer=None,linuxBuild=None):
"""Get image by parameters"""
# exclude directory distributive for flash and scratch install
if scratch == "on" or rootType == "flash":
@ -93,43 +84,40 @@ class DistroRepository(Linux):
version=linuxVer,
build=linuxBuild)
def _getAvailableShortnames(self, dirs):
def _getAvailableShortnames(self,dirs):
"""Get available distributives shortnames"""
distros = [x for x
in map(self.reDistName.search, self._getAvailableDistributives(dirs))
if x]
return sorted(list(set([x.groupdict()['name'] for x in distros])))
def opcompareByString(self, buf):
distros = filter(lambda x:x,
map(self.reDistName.search,self._getAvailableDistributives(dirs)))
return sorted(list(set(map(lambda x:x.groupdict()['name'],distros))))
def opcompareByString(self,buf):
if buf:
reOp = re.compile("^(!=|=|==|<=|>=|>|<)?(\d+.*)$")
res = reOp.search(buf)
if res:
return ({'!=': operator.ne,
'=': operator.eq,
'==': operator.eq,
'>=': operator.ge,
'<=': operator.le,
'<': operator.lt,
'>': operator.gt}.get(res.group(1), operator.eq),
return ({'!=':operator.ne,
'=':operator.eq,
'==':operator.eq,
'>=':operator.ge,
'<=':operator.le,
'<':operator.lt,
'>':operator.gt}.get(res.group(1),operator.eq),
res.group(2))
else:
return operator.eq, buf
return None, None
return operator.eq,buf
return None,None
def _getAvailableDistributives(self, dirs, system=None, shortname=None,
march=None, version=None, build=None):
def _getAvailableDistributives(self,dirs,system=None,shortname=None,
march=None,version=None,build=None):
"""Get all distributives by filter"""
def systemByName(name):
return self.dictNameSystem.get(name.upper(), "")
return self.dictNameSystem.get(name.upper(),"")
verCmp, version = self.opcompareByString(version)
if version:
version = getTupleVersion(version)
buildCmp, build = self.opcompareByString(build)
if build and build.isdigit():
build = int(build)
def distfilter(dist):
d = self._getDistrInfo(dist)
if not d:
@ -137,123 +125,119 @@ class DistroRepository(Linux):
# check filter conditions
if system and systemByName(d['os_linux_shortname']) != system:
return False
if "os_linux_shortname" not in d or "os_linux_ver" not in d:
if not "os_linux_shortname" in d or not "os_linux_ver" in d:
return False
if (shortname and
d['os_linux_shortname'].lower() != shortname.lower()):
if shortname and \
d['os_linux_shortname'].lower() != shortname.lower():
return False
if march and d['os_arch_machine'] != march:
return False
if version and \
not verCmp(getTupleVersion(d['os_linux_ver']), version):
not verCmp(getTupleVersion(d['os_linux_ver']), version):
return False
if build and "os_linux_build" in d and \
(not d['os_linux_build'].isdigit() or
not buildCmp(int(d['os_linux_build']), build)):
(not d['os_linux_build'].isdigit() or
not buildCmp(int(d['os_linux_build']),build)):
return False
return True
def listdistr(pathname):
if path.exists(path.join(pathname, 'etc/make.profile')) or \
path.exists(
path.join(pathname, 'etc/portage/make.profile')) or \
path.exists(path.join(pathname, 'livecd')) or \
pathname.startswith('/dev/'):
if path.exists(path.join(pathname,'etc/make.profile')) or \
path.exists(path.join(pathname,'etc/portage/make.profile')) or \
path.exists(path.join(pathname,'livecd')) or \
pathname.startswith('/dev/'):
return [pathname]
else:
# discard inner directories
return [x for x in listDirectory(pathname) if not path.isdir(path.join(pathname, x))]
return filter(lambda x:not path.isdir( path.join(pathname,x)),
listDirectory(pathname))
# get lists files in directories
allFiles = [[path.join(x, y) for y in listdistr(x)] for x in dirs]
allFiles = map(lambda x: map(lambda y: path.join(x,y),
listdistr(x)),
dirs)
# filter distributives
# join files lists to one list
return [x for x in reduce(lambda x, y: x + y, allFiles, []) if distfilter(x)]
return filter(distfilter,
# join files lists to one list
reduce(lambda x,y: x + y,
allFiles, []))
@staticmethod
def extcomparator(ext1, ext2):
def extcomparator(self,*exts):
"""Compare extensions"""
mapExts = {'iso': 0,
'flash': -1,
'isodir': -2,
'partdir': -3,
'dir': -4}
return cmp(mapExts.get(ext1, -4), mapExts.get(ext2, -4))
@staticmethod
def sortdistrfunc(x, y):
mapExts = {'iso':0,
'flash':-1,
'isodir':-2,
'partdir':-3,
'dir':-4}
return cmp(mapExts.get(exts[0],-4),mapExts.get(exts[1],-4))
def sortdistrfunc(self,x,y):
"""Func of comparing two distributive"""
ver1, ver2 = x[1].get('os_linux_ver', ""), y[1].get('os_linux_ver', "")
ver1, ver2 = x[1].get('os_linux_ver',""), y[1].get('os_linux_ver',"")
if ver1 and ver2 and ver1 != "0" and ver2 != "0" and ver1 != ver2:
return cmpVersion(ver1, ver2)
build1 = getTupleVersion(x[1].get('os_linux_build', ""))
build2 = getTupleVersion(y[1].get('os_linux_build', ""))
if build1 != build2:
return cmp(build1, build2)
return cmpVersion(ver1,ver2)
build1 = getTupleVersion(x[1].get('os_linux_build',""))
build2 = getTupleVersion(y[1].get('os_linux_build',""))
if build1 != build2:
return cmp(build1,build2)
else:
ser1, ser2 = (x[1].get('serial_id') or "0",
y[1].get('serial_id') or "0")
if ser1 != ser2:
return cmp(int(ser1), int(ser2))
ext1 = x[1].get('ext', "")
ext2 = y[1].get('ext', "")
return DistroRepository.extcomparator(ext1, ext2)
def getAvailableDristibutives(self, dirs, system=None, shortname=None,
march=None, version=None, build=None,
discardType=()):
ext1 = x[1].get('ext',"")
ext2 = y[1].get('ext',"")
return self.extcomparator(ext1,ext2)
def getAvailableDristibutives(self,dirs,system=None,shortname=None,
march=None, version=None, build=None,discardType=[]):
"""Get list available distributives"""
if shortname:
shortname = shortname.lower()
availDistrs = self._getAvailableDistributives(dirs, system, shortname,
march, version,
build)
availDistrs = (x for x
in [(y, self._getDistrInfo(y)) for y in availDistrs]
if x[1] and "ext" in x[1] and not x[1]["ext"] in discardType)
return [x[0] for x in sorted(availDistrs, key=cmp_to_key(DistroRepository.sortdistrfunc), reverse=True)]
def getBestDistributive(self, dirs, system=None, shortname=None, march=None,
version=None, build=None, discardType=()):
availDistrs = self._getAvailableDistributives(dirs,system,shortname,
march,version,
build)
availDistrs = filter(lambda x:x[1] and "ext" in x[1] and
not x[1]["ext"] in discardType,
map(lambda x:(x,self._getDistrInfo(x)),
availDistrs))
return map(lambda x:x[0],
sorted(availDistrs,self.sortdistrfunc,reverse=True))
def getBestDistributive(self,dirs,system=None,shortname=None,march=None,
version=None, build=None,discardType=[]):
"""Get the actualest distributive"""
availDistrs = self.getAvailableDristibutives(dirs, system, shortname,
march, version, build,
discardType)
availDistrs = self.getAvailableDristibutives(dirs,system,shortname,
march,version,build,discardType)
if availDistrs:
return availDistrs[0]
else:
return None
def _findLatestFile(self, dirs, reMatch, keyfunc):
def _findLatestFile(self,dirs,reMatch,keyfunc):
"""Find latest file in dirs, which match by reMatch,
comparable part get by keyfunc"""
existsdirs = list(filter(path.exists, dirs))
listimgs = reduce(lambda x, y: x + list(map(
lambda x: reMatch.search(
path.join(y, x)),
listDirectory(y))),
existsdirs, [])
listimgs = [x for x in listimgs if x]
existsdirs = filter(path.exists,dirs)
listimgs = reduce(lambda x,y:x + \
map(lambda x:reMatch.search(path.join(y,x)),
listDirectory(y)),
existsdirs,[])
listimgs = filter(lambda x:x, listimgs)
if listimgs:
return max(listimgs, key=keyfunc).group()
return max(listimgs,key=keyfunc).group()
return ""
def getBestStage(self, dirs, march=None, hardened=None):
def getBestStage(self,dirs,march=None,hardened=None):
"""Get latest stage by march"""
if march:
march = {'x86_64': 'amd64'}.get(march, march)
march = {'x86_64':'amd64'}.get(march,march)
else:
march = "[^-]+"
if hardened is None:
hardened = "(?:-hardened)?"
elif hardened is True:
elif hardened == True:
hardened = "-hardened"
elif hardened is False:
elif hardened == False:
hardened = ""
reStage = re.compile(r'^.*/stage3-%s%s-(\d+)\.tar\.bz2$' %
(march, hardened), re.S)
return self._findLatestFile(dirs, reStage, lambda x: x.groups()[0])
reStage = re.compile(r'^.*/stage3-%s%s-(\d+)\.tar\.bz2$'%
(march,hardened),re.S)
return self._findLatestFile(dirs,reStage,lambda x:x.groups()[0])
class VariableClImage(ReadonlyVariable):
@ -265,8 +249,7 @@ class VariableClImage(ReadonlyVariable):
def get(self):
"""Get image file from distributive repository"""
try:
action = self.Get('cl_action')
if not action in ('system',):
if not self.Get('cl_action') in ('system','prepare'):
return Distributive.fromFile('/')
filename = self.Get('cl_image_filename')
if filename:
@ -281,8 +264,7 @@ class VariableClImage(ReadonlyVariable):
return filename.getType()
return filename
class VariableClImageFilename(DistroRepository, Variable):
class VariableClImageFilename(Variable,DistroRepository):
"""
Distributive image filename
"""
@ -290,7 +272,6 @@ class VariableClImageFilename(DistroRepository, Variable):
element = 'file'
metavalue = "IMAGE"
opt = ['--iso']
check_after = ["os_install_root_type"]
untrusted = True
def init(self):
@ -302,55 +283,44 @@ class VariableClImageFilename(DistroRepository, Variable):
return ""
arch = self.Get('cl_image_arch_machine') or self.Get('os_arch_machine')
shortname = self.Get('cl_image_linux_shortname') or \
self.Get('os_linux_shortname')
self.Get('os_linux_shortname')
ver = self.Get('cl_image_linux_ver') or None
build = self.Get('cl_image_linux_build') or None
return self.getImage(self.Get('os_install_scratch'),
self.Get('os_install_root_type'),
self.Get('cl_image_path'),
arch, shortname, ver, build) or ""
self.Get('os_install_root_type'),
self.Get('cl_image_path'),
arch,shortname,ver,build) or ""
def check(self, isoimage):
def check(self,isoimage):
"""Set image file"""
if self.Get('cl_action') == 'system' and not isoimage:
raise VariableError(_("You need to select a distribution image"))
try:
d = Distributive.fromFile(isoimage)
if isinstance(d, ArchiveDistributive):
raise VariableError(_("Wrong image file"))
except DistributiveError:
pass
imageData = Distributive().getInfo(isoimage)
if not ("os_linux_shortname" in imageData and
imageData.get('os_linux_build', '') and
"os_arch_machine" in imageData):
if not("os_linux_shortname" in imageData and \
imageData.get('os_linux_build','') and \
"os_arch_machine" in imageData):
raise VariableError(_("Wrong image file"))
if imageData["os_chrootable_set"] == 'off':
raise VariableError(
_("The image is not compatible with the current kernel"))
def humanImageName(self, distroinfo, filepath):
def humanImageName(self,distroinfo,filepath):
if all(x in distroinfo for x in ("os_linux_shortname",
"os_arch_machine",
"os_linux_build")):
distroinfo['os_linux_shortname'] = \
distroinfo['os_linux_shortname'].upper()
fullname = distroinfo.get('os_linux_name',
Linux.dictLinuxName.get(
distroinfo['os_linux_shortname'],
"Calculate"))
Linux.dictLinuxName.get(
distroinfo['os_linux_shortname'],"Calculate"))
subname = distroinfo.get('os_linux_subname',
Linux.dictLinuxSubName.get(
distroinfo['os_linux_shortname'], ""))
Linux.dictLinuxSubName.get(
distroinfo['os_linux_shortname'],""))
if subname:
subname = " %s" % subname
subname=" %s"%subname
build = distroinfo['os_linux_build'] or \
distroinfo.get('os_linux_ver', '')
ver = distroinfo.get('os_linux_ver', '')
distroinfo.get('os_linux_ver','')
ver = distroinfo.get('os_linux_ver','')
return "{fullname} {os_arch_machine} {build}".format(
fullname="%s%s" % (fullname, subname), filepath=filepath,
build=build, ver=ver, **distroinfo)
fullname="%s%s"%(fullname,subname),filepath=filepath,
build=build,ver=ver,**distroinfo)
else:
return filepath
@ -358,32 +328,33 @@ class VariableClImageFilename(DistroRepository, Variable):
fullname = self.Get('os_install_linux_name')
subname = self.Get('os_install_linux_subname')
if subname:
subname = " %s" % subname
subname = " %s"%subname
arch = self.Get('os_install_arch_machine')
build = self.Get('os_install_linux_build')
ver = self.Get('os_install_linux_ver')
return "{fullname} {ver} {arch} {build}".format(
fullname="%s%s" % (fullname, subname),
build=build, ver=ver, arch=arch)
fullname="%s%s"%(fullname,subname),
build=build,ver=ver,arch=arch)
def choice(self):
scratch = self.Get('os_install_scratch')
rootType = self.Get('os_install_root_type')
imagePath = self.Get('cl_image_path')
if scratch == "on" or rootType == "flash" or \
self.Get('cl_install_type') == 'flash':
self.Get('cl_install_type') == 'flash':
discardType = ["dir"]
else:
discardType = []
distros = self.getAvailableDristibutives(imagePath,
discardType=discardType)
discardType=discardType)
if self.wasSet and not self.value in distros:
distros.append(self.value)
return sorted(((x, self.humanImageName(self._getDistrInfo(x), x)) for x in distros), key=itemgetter(1))
return sorted(map(lambda x:(x,
self.humanImageName(self._getDistrInfo(x),x)),
distros),key=itemgetter(1))
class VariableClImageArchMachine(DistroRepository, Variable):
class VariableClImageArchMachine(Variable,DistroRepository):
"""
Filter by architecture
"""
@ -391,83 +362,73 @@ class VariableClImageArchMachine(DistroRepository, Variable):
type = 'choice'
opt = ['--march']
metavalue = "ARCH"
available_arch = ["x86_64"]
available_arch = ["i686","x86_64"]
def init(self):
self.label = "%s %s" % (_("Filter"), _("by processor architecture"))
self.label = "%s %s"%(_("Filter"),_("by processor architecture"))
self.help = _("select the processor architecture")
def set(self, march):
def set(self,march):
if march == "auto":
march = getSupportArch()[-1]
return march
def choice(self):
return [("", _("Not used"))] + \
[("auto", _("Auto"))] + \
[(x, x) for x in self.available_arch]
return [("",_("Not used"))]+\
[("auto",_("Auto"))] + \
[(x,x) for x in self.available_arch]
def humanReadable(self):
return self.Get() or _("Not used")
class VariableClImageLinuxShortname(DistroRepository, Variable):
class VariableClImageLinuxShortname(Variable,Linux,DistroRepository):
"""
Filter by shortname
"""
value = ""
type = 'choiceedit'
metavalue = "SYSTEM"
opt = ['--os', '-s']
opt = ['--os','-s']
def init(self):
self.label = "%s %s" % (_("Filter"), _("by distribution"))
self.label = "%s %s"%(_("Filter"),_("by distribution"))
self.help = _("select the operation system")
def choice(self):
return [("", _("Not used"))] + [
("CLD", "Calculate Linux Desktop KDE"),
("CLDM", "Calculate Linux Desktop MATE"),
("CLDX", "Calculate Linux Desktop XFCE"),
("CLS", "Calculate Linux Scratch"),
("CDS", "Calculate Directory Server"),
("CSS", "Calculate Scratch Server"),
("CMC", "Calculate Media Center"),
]
return [("",_("Not used"))]+\
sorted(map(lambda x:(x,self.getFullNameByShort(x)),
self.dictLinuxName.keys()),
key=itemgetter(1))
def humanReadable(self):
return self.Get() or _("Not used")
class VariableClImageLinuxVer(DistroRepository, Variable):
class VariableClImageLinuxVer(Variable,DistroRepository):
"""
Filter by version
"""
value = ""
def init(self):
self.label = "%s %s" % (_("Filter"), _("by version"))
self.label = "%s %s"%(_("Filter"),_("by version"))
self.help = _("select the operation system by version")
def humanReadable(self):
return self.Get() or _("Not used")
class VariableClImageLinuxBuild(DistroRepository, Variable):
class VariableClImageLinuxBuild(Variable,DistroRepository):
"""
Filter by build
"""
value = ""
def init(self):
self.label = "%s %s" % (_("Filter"), _("by build"))
self.label = "%s %s"%(_("Filter"),_("by build"))
self.help = _("select the operation system by build")
def humanReadable(self):
return self.Get() or _("Not used")
class VariableClImagePath(ReadonlyVariable):
"""
Image search path
@ -487,26 +448,22 @@ class VariableClImagePath(ReadonlyVariable):
livedistr = ['/mnt/livecd']
# standard livecd
else:
if self.Get('os_install_root_type') == "flash":
livedistr = ['/run/initramfs/live',
'/run/initramfs/squashfs',
'/mnt/cdrom']
else:
livedistr = ['/run/initramfs/squashfs',
'/run/initramfs/live',
'/mnt/cdrom']
livedistr = [x for x in livedistr if listDirectory(x)][:1]
livedistr = ['/run/initramfs/squashfs',
'/run/initramfs/live',
'/mnt/cdrom']
else:
livedistr = []
# search all partition for source installation distributive
rootDev = self.Get('os_install_root_dev')
livedistr += [x[0] for x
in zip(self.Get('os_disk_dev'), self.Get('os_disk_content'))
if " live" in x[1] and x[0] != rootDev]
livedistr += \
map(lambda x:x[0],
filter(lambda x:" live" in x[1] and x[0] != rootDev,
zip(self.Get('os_disk_dev'),
self.Get('os_disk_content'))))
# add to standard path
return [x for x in ['/var/calculate/remote/linux',
'/var/calculate/linux'] + livedistr if path.exists(x)]
return filter(path.exists,
['/var/calculate/remote/linux',
'/var/calculate/linux'] + livedistr)
class VariableClSource(ReadonlyVariable):
"""
@ -517,13 +474,11 @@ class VariableClSource(ReadonlyVariable):
def get(self):
return DirectoryDistributive('/')
class VariableClTarget(ReadonlyVariable):
"""
Target distributive
"""
type = "object"
filesystem = "cl_target_fs"
def get(self):
listVars = ['os_install_disk_dev', 'os_install_disk_mount',
@ -533,145 +488,101 @@ class VariableClTarget(ReadonlyVariable):
short=self.Get('os_install_linux_shortname'),
ver=self.Get('os_install_linux_ver'))
if self.Get('os_install_root_type') == "flash":
flashLabel = "{short}-{build}".format(
short="CL", build=self.Get('os_install_linux_build'))
disk = self.Get('os_install_disk_single')
fileSystem = self.Get(self.filesystem) or 'ntfs'
#fileSystem = "vfat"
systemId = FileSystemManager.supportFS.get(
fileSystem, {}).get('msdos', '0b')
isFormat = self.GetBool('os_install_format_single_set')
partTable = self.select('os_disk_part',
os_disk_dev=disk, limit=1)
return FlashDistributive(
disk, mdirectory=DefaultMountPath.InstallMount,
check=True, fileSystem=fileSystem,
isFormat=isFormat, systemId=systemId,
rootLabel=flashLabel,
partitionTable=partTable)
osInstallScratch = self.isTrue(self.Get('os_install_scratch'))
mapDevId = dict(self.ZipVars('os_disk_dev', 'os_disk_id'))
disk, mount, fileSystem, isFormat, partTable, systemId = \
mapDevId = dict(self.ZipVars('os_disk_dev','os_disk_id'))
disk, mount, fileSystem, isFormat, partTable,systemId = \
self.Select(listVars,
where='os_install_disk_mount',
eq='/', limit=1)
if not systemId or mapDevId.get(disk, '') == systemId:
eq='/',limit=1)
if not systemId or mapDevId.get(disk,'') == systemId:
systemId = None
if osInstallScratch:
raise VariableError("Scratch is not supported")
if self.Get('os_install_pxe') == "on":
target = ScratchPartitionDistributive(disk,mdirectory='/mnt/install',
check=True,fileSystem=fileSystem,
isFormat=self.isTrue(isFormat),
systemId=systemId,
partitionTable=partTable)
elif self.Get('os_install_pxe') == "on":
return PxeDistributive(self.Get('os_install_pxe_path'))
elif self.Get('os_install_root_type')=="flash":
flashLabel = "{short}-{build}".format(
short="CL", build=self.Get('os_install_linux_build'))
return FlashDistributive(disk,mdirectory="/mnt/install",
check=True, fileSystem=fileSystem,
isFormat=isFormat, systemId=systemId,
rootLabel=flashLabel,
partitionTable=partTable)
else:
target = PartitionDistributive(
disk, mdirectory=DefaultMountPath.InstallMount,
check=True, fileSystem=fileSystem,
rootLabel=rootLabel,
isFormat=self.isTrue(isFormat),
systemId=systemId,
partitionTable=partTable,
compression=self.Get('os_install_btrfs_compression'))
target = PartitionDistributive(disk,mdirectory='/mnt/install',
check=True,fileSystem=fileSystem,
rootLabel=rootLabel,
isFormat=self.isTrue(isFormat),
systemId=systemId,
partitionTable=partTable)
multiPartition = None
diskData = self.Select(listVars,
where='os_install_disk_mount',
ne='/')
bindData = self.Select(['os_install_bind_path',
'os_install_bind_mountpoint'],
where='os_install_bind_mountpoint',
ne='')
where='os_install_bind_mountpoint',
ne='')
if diskData or bindData:
multiPartition = MultiPartitions()
target.multipartition = multiPartition
for disk, mount, fileSystem, isFormat, partTable, systemId in diskData:
if not systemId or mapDevId.get(disk, '') == systemId:
for disk,mount,fileSystem,isFormat,partTable,systemId in diskData:
if not systemId or mapDevId.get(disk,'') == systemId:
systemId = None
multiPartition.addPartition(dev=disk,
mountPoint=mount,
fileSystem=fileSystem,
isFormat=self.isTrue(isFormat),
systemId=systemId,
partitionTable=partTable)
for source, dest in bindData:
mountPoint=mount,
fileSystem=fileSystem,
isFormat=self.isTrue(isFormat),
systemId=systemId,
partitionTable=partTable)
for source,dest in bindData:
multiPartition.addPartition(dev=source,
mountPoint=dest,
fileSystem='bind',
isFormat=False,
systemId=None,
partitionTable='')
mountPoint=dest,
fileSystem='bind',
isFormat=False,
systemId=None,
partitionTable='')
return target
class VariableClTargetFs(Variable):
type = 'choice'
opt = ['--fs']
disk = 'os_install_disk_single'
value = 'auto'
metavalue = 'FS_NAME'
def init(self):
self.label = _("File system on flash device")
self.help = _("Create new FS on flash device(formating req)")
def get(self):
if self.value != 'auto':
return self.value
return 'vfat'
def choice(self):
return ['vfat', 'btrfs', 'ntfs', 'ext4',
'ext3', 'ext2', 'xfs']
class VariableClImageNewOnly(Variable):
"""
Distributive image filename
"""
type = 'bool'
opt = ['-U', '--update']
opt = ['-U','--update']
value = "off"
def init(self):
self.label = _("Install the newer image only")
self.help = _("install the newer image only")
def installedBuild(self):
"""
Get build already installed system
Need for check update
"""
imageData = None
rootDev = self.Get('os_install_root_dev')
if not rootDev:
return ""
try:
imageData = Distributive().getInfo(rootDev)
return imageData.get('os_linux_build', '')
except Exception:
return imageData.get('os_linux_build','')
except:
pass
return ""
def check(self, value):
def check(self,value):
if value == 'on':
try:
imageData = Distributive().getInfo(
self.Get('cl_image_filename'))
imageData = Distributive().getInfo(self.Get('cl_image_filename'))
except Exception as e:
raise VariableError(_("Wrong image file"))
if imageData.get('os_linux_build', '') <= \
self.Get('os_linux_build'): #or \
# imageData.get('os_linux_build',
# '') <= self.installedBuild():
if imageData.get('os_linux_build','') <= \
self.Get('os_linux_build') or \
imageData.get('os_linux_build','') <= self.installedBuild():
raise CommonVariableError(_("The image for update not found"))
if imageData.get('os_linux_build', '') <= self.installedBuild():
raise BuildAlreadyInstalledError(_("Build already installed"))
class VariableClInstallPathFrom(ReadonlyVariable):
"""
Путь из устанавливаемой системы до устанавливающий системы
"""
def get(self):
template_path = pathJoin(self.Get('cl_chroot_path'),
self.Get('cl_root_path'))
return os.path.relpath("/", template_path)

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -18,26 +18,20 @@ import os
import sys
import re
from os import path
from calculate.lib.datavars import (Variable, ReadonlyVariable,
ReadonlyTableVariable, FieldValue,
HumanReadable, VariableInterface)
from calculate.lib.utils.files import (readFile,
typeFile, process, listDirectory,
MAGIC_SYMLINK, MAGIC_COMPRESS)
from calculate.lib.utils.kernel import InitrdFile
from calculate.lib.datavars import Variable,VariableError,ReadonlyVariable
from calculate.lib.utils.files import (
typeFile,process,listDirectory,MAGIC_SYMLINK,MAGIC_COMPRESS)
from calculate.lib.cl_lang import setLocalTranslate
_ = lambda x: x
setLocalTranslate('cl_install3', sys.modules[__name__])
setLocalTranslate('cl_install3',sys.modules[__name__])
from operator import itemgetter
from calculate.lib.utils.files import readLinesFile
from calculate.lib.utils.common import (getKernelUid, getTupleVersion,
getValueFromCmdLine, CmdlineParams)
from calculate.lib.utils.files import readLinesFile,pathJoin
from calculate.lib.utils.common import (getKernelUid,getTupleVersion,
getValueFromCmdLine)
from calculate.lib.utils.device import getUdevDeviceInfo
from itertools import *
from ..distr import DistributiveError
from calculate.install.distr import DistributiveError
class VariableOsInstallKernelScheduler(Variable):
"""
@ -51,50 +45,30 @@ class VariableOsInstallKernelScheduler(Variable):
self.help = _("toggle the I/O scheduler")
self.label = _("I/O scheduler")
def check_scheduler(self, scheduler):
return scheduler in self.Select('os_install_kernel_schedule_name',
where='os_install_kernel_schedule_set',
eq='on')
def get_default(self):
root_devs = self.Select('os_install_disk_parent',
where='os_install_disk_mount',
eq='/', limit=1).split(',')
for root_dev in root_devs:
dev_ssd, dev_virtual = self.Select(['os_device_ssd_set',
'os_device_virtual_set'],
where='os_device_dev',
eq=root_dev, limit=1)
if ((dev_ssd == 'on' or dev_virtual == 'on') and
self.check_scheduler("noop")):
return "noop"
return self.Get('os_install_kernel_schedule_default')
def get(self):
"""Get scheduler for install root device"""
if self.Get('os_root_type') == 'livecd':
return self.get_default()
root_dev = self.Select('os_install_disk_parent',
where='os_install_disk_mount',
eq='/',limit=1)
if root_dev:
dev_ssd = self.Select('os_device_ssd_set',
where='os_device_dev',
eq=root_dev,limit=1)
if dev_ssd == 'on':
return "noop"
else:
currentScheduler = getValueFromCmdLine(
CmdlineParams.IOScheduler)
if currentScheduler in (x[0] for x in self.choice()):
currentScheduler = getValueFromCmdLine('elevator',0)
if currentScheduler in map(lambda x:x[0],self.choice()):
return currentScheduler
return self.Get('os_install_kernel_schedule_default')
return "cfq"
def choice(self):
schedulers = {"deadline": "Deadline",
"cfq": "CFQ",
"noop": "No-op",
"bfq": "BFQ"}
return [(x, schedulers.get(x, x))
for x in self.Select('os_install_kernel_schedule_name',
where='os_install_kernel_schedule_set',
eq='on')] + [("auto", _("Default"))]
def set(self, value):
if value == "auto":
return self.get_default()
return value
schedulers = [("deadline","Deadline"),("cfq","CFQ"),("noop","No-op")]
if self.Get('os_install_kernel_bfq_set') == 'on':
return schedulers + [("bfq","BFQ")]
else:
return schedulers
def uncompatible(self):
"""
@ -103,325 +77,141 @@ class VariableOsInstallKernelScheduler(Variable):
if self.Get('os_install_root_type') == 'flash':
return _("I/O scheduler unavailable for Flash install")
class KernelConfig():
def __init__(self, kernel_config):
self.data = readFile(kernel_config).split('\n')
self.config = kernel_config
def __iter__(self):
return iter(self.data)
def __str__(self):
return "kernel config (%s)" % self.config
def __len__(self):
return len(self.data)
def __contains__(self, item):
if "=" in item:
if item.endswith("=n"):
key = "# %s is not set" % item[:-2]
else:
key = item
else:
key = "%s=" % item
return any(key in x for x in self)
class VariableOsInstallKernelConfig(ReadonlyVariable):
class VariableOsInstallKernelBfqSet(ReadonlyVariable):
"""
Install config kernel filename
Available BFQ in kernel
"""
def get_kernel_src(self, distr_path):
"""
Get version of kernel from .config
"""
kernel_src = 'usr/src/linux'
makefile_path = path.join(distr_path, kernel_src, "Makefile")
# get version from Makefile
re_makefile = re.compile("^VERSION = (\S+)\n"
"PATCHLEVEL = (\S+)\n"
"SUBLEVEL = (\S+)\n"
"EXTRAVERSION = (\S*)\n", re.M)
if path.exists(makefile_path):
with open(makefile_path) as f:
match = re_makefile.search(f.read(200))
if match:
return "{0}.{1}.{2}{3}".format(*match.groups())
return ""
def configs(self, distr_path):
src_kernel_ver = self.get_kernel_src(distr_path)
if src_kernel_ver:
yield path.join("boot", "config-%s" % src_kernel_ver)
if self.Get('cl_chroot_path') == '/':
ver = process('/bin/uname', '-r').read().strip()
yield path.join("boot", "config-%s" % ver)
yield 'usr/src/linux/.config'
type = "bool"
def get(self):
image = self.Get('cl_image')
if image:
with image:
with image as distr:
try:
distrPath = image.getDirectory()
for config in self.configs(distrPath):
config_name = path.join(distrPath, config)
if path.exists(config_name):
return KernelConfig(config_name)
except DistributiveError:
return ""
return ""
class VariableOsKernelConfig(VariableOsInstallKernelConfig):
"""
Current config kernel
"""
def configs(self, distr_path):
ver = process('/bin/uname', '-r').read().strip()
yield path.join("boot", "config-%s" % ver)
yield 'usr/src/linux/.config'
def get(self):
for config in self.configs("/"):
config_name = path.join("/", config)
if path.exists(config_name):
return KernelConfig(config_name)
return ""
class VariableOsInstallKernelScheduleDefault(Variable):
"""
IO планировщик по умолчанию
"""
type = "choice"
def get(self):
for line in self.Get('os_install_kernel_config'):
if "CONFIG_DEFAULT_IOSCHED=" in line:
key, op, value = line.partition("=")
return value.strip('"')
return "cfq"
def choice(self):
return self.Select('os_install_kernel_schedule_name',
where='os_install_kernel_schedule_set',
eq='on')
class VariableOsInstallKernelScheduleData(ReadonlyTableVariable):
"""
Information about kernel schedule
"""
source = ['os_install_kernel_schedule_name',
'os_install_kernel_schedule_set']
def get(self, hr=HumanReadable.No):
schedulers = {'CONFIG_IOSCHED_BFQ=y': 'bfq',
'CONFIG_IOSCHED_NOOP=y': 'noop',
'CONFIG_IOSCHED_CFQ=y': 'cfq',
'CONFIG_IOSCHED_DEADLINE=y': 'deadline'}
installed = [schedulers.get(x) for x
in self.Get('os_install_kernel_config')
if x in schedulers] or ['cfq']
return [[x, "on" if x in installed else "off"]
for x in sorted(schedulers.values())]
setValue = Variable.setValue
class VariableOsInstallKernelScheduleName(FieldValue, ReadonlyVariable):
"""
Schedule name
"""
type = "list"
source_variable = "os_install_kernel_schedule_data"
column = 0
class VariableOsInstallKernelScheduleSet(FieldValue, ReadonlyVariable):
"""
Kernel has schedule
"""
type = "list-bool"
source_variable = "os_install_kernel_schedule_data"
column = 1
class VariableOsInstallKernelTuxoniceSet(ReadonlyVariable):
"""
Available BFQ in kernel
"""
type = "bool"
def get(self):
if any("CONFIG_TOI_CORE=y" in x
for x in self.Get('os_install_kernel_config')):
return "on"
return "off"
class VariableOsInstallKernelBfqSet(ReadonlyVariable):
"""
Available BFQ in kernel
"""
type = "bool"
def get(self):
if any("CONFIG_IOSCHED_BFQ=y" in x
for x in self.Get('os_install_kernel_config')):
return "on"
return "off"
class VariableOsInstallNomodeset(Variable):
type = "bool"
def get(self):
cmdLine = '/proc/cmdline'
if 'nomodeset' in readFile(cmdLine):
return "on"
kernelConfig = path.join(distrPath,"usr/src/linux/.config")
if filter(lambda x:"CONFIG_IOSCHED_BFQ=y" in x,
readLinesFile(kernelConfig)):
return "on"
except DistributiveError as e:
return "off"
return "off"
class VariableOsInstallKernelAttr(Variable):
"""
Install kernel attributes
"""
def get(self):
def generate():
# 5 sec for usb hdd boot
if self.GetBool('os_install_nomodeset'):
yield "nomodeset"
if self.Get('os_install_root_type') == 'usb-hdd':
yield "scandelay=5"
if (self.GetBool('os_install_mdadm_set') or
self.GetBool('os_install_lvm_set')):
yield "rd.auto"
yield "rd.retry=40"
return " ".join(generate())
# on usb-hdd install must be "delay=5"
attr = ""
rdauto = ""
if self.Get('os_install_root_type') == 'usb-hdd':
attr = " scandelay=5"
if self.Get('os_install_mdadm_set') == 'on':
attr += " domdadm"
rdauto = " rd.auto"
if self.Get('os_install_lvm_set') == 'on':
attr += " dolvm"
if not rdauto:
rdauto = " rd.auto"
return attr + rdauto
class VariableOsInstallKernelResume(ReadonlyVariable):
"""
Install kernel resume
"""
def get(self):
"""install kernel resume parameter"""
for dev, partuuid, install in zip(self.Get('os_install_disk_use'),
self.Get('os_install_disk_partuuid'),
self.Get('os_install_disk_mount')):
for dev, install in zip(self.Get('os_install_disk_use'),
self.Get('os_install_disk_mount')):
if install == "swap":
if self.Get('os_install_kernel_tuxonice_set') == 'on':
return "tuxonice tuxonice_resume=%s real_resume=%s" % (
dev, dev)
if self.Get('os_install_linux_system') == 'desktop':
return \
"tuxonice tuxonice_resume=%s real_resume=%s"%(dev,dev)
else:
if partuuid:
return "resume=PARTUUID=%s" % partuuid
else:
return "resume=%s" % dev
return "real_resume=%s"%dev
return ""
class KernelHelper(VariableInterface):
class KernelHelper:
"""
Helper for kernel variables
"""
reFindVer = re.compile(
"(?<=version )(\d+\.?\d*\.?\d*\.?\d*)([^\d* ])*(\d*)")
def getFilesByType(self, pathname, descr):
def getFilesByType(self,pathname,descr):
"""Get files from "pathname" has "descr" in descriptions"""
filelist = [path.join(pathname, x) for x in os.listdir(pathname)]
ftype = typeFile(magic=MAGIC_COMPRESS | MAGIC_SYMLINK).getMType
filesWithType = [(x, ftype(x)) for x in filelist if path.exists(x)]
return [x for x in filesWithType if x[1] and descr in x[1]]
def getInitrdFiles(self, pathname):
filelist = [path.join(pathname, x) for x in os.listdir(pathname)]
return [x for x in filelist if path.exists(x) and InitrdFile.is_cpio(x)]
def getInitrd(self, arch, shortname, chroot, kernel, suffix="",
notsuffix=""):
filelist = map(lambda x:path.join(pathname,x),os.listdir(pathname))
ftype = typeFile(magic=MAGIC_COMPRESS|MAGIC_SYMLINK).getMType
filesWithType = map(lambda x:(x,ftype(x)),
filter(path.exists,
filelist))
return filter(lambda x:descr in x[1],filesWithType)
def getInitrd(self,arch,shortname,chroot,kernel,suffix="",notsuffix=""):
"""Get initrd for kernel"""
reInitrdVer = re.compile("(initrd|initramfs)-(.+?)(-install)?$", re.S)
reInitrdVer = re.compile("(initrd|initramfs)-(.+?)(-install)?$",re.S)
def initrd_version_by_name(filename):
resInitrdVer = reInitrdVer.search(filename)
if resInitrdVer:
return resInitrdVer.groups()[1]
return ""
ftype = typeFile(magic=MAGIC_COMPRESS | MAGIC_SYMLINK).getMType
kernelfile = path.join(chroot, 'boot', kernel)
ftype = typeFile(magic=MAGIC_COMPRESS|MAGIC_SYMLINK).getMType
kernelfile = path.join(chroot,'boot',kernel)
typeKernelFile = ftype(kernelfile)
if typeKernelFile is None:
if typeKernelFile == None:
return ""
resKernelVer = self.reFindVer.search(ftype(kernelfile))
if resKernelVer:
kernelVersion = "%s-%s-%s" % \
(resKernelVer.group().replace('-calculate', ''),
arch, shortname)
kernelVersion = "%s-%s-%s"% \
(resKernelVer.group().replace('-calculate',''),
arch, shortname)
origKernelVer = resKernelVer.group()
bootdir = path.join(chroot, 'boot')
initramfsFiles = self.getInitrdFiles(bootdir)
initramfsWithVer = [x for x
in [(y, initrd_version_by_name(y)) for y in initramfsFiles]
if (kernelVersion in x[1] or
origKernelVer in x[1]) and
x[0].endswith(suffix) and
(not notsuffix or not x[0].endswith(notsuffix))]
bootdir = path.join(chroot,'boot')
initramfsFiles = self.getFilesByType(bootdir,"ASCII cpio archive")
initramfsWithVer = \
filter(lambda x: (kernelVersion in x[1] or
origKernelVer in x[1]) and \
x[0].endswith(suffix) and \
(not notsuffix or not x[0].endswith(notsuffix)),
map(lambda x:(x[0],initrd_version_by_name(x[0])),
initramfsFiles))
if initramfsWithVer:
return path.split(min(initramfsWithVer,
key=itemgetter(0))[0])[-1]
key=itemgetter(0))[0])[-1]
return ""
class VariableOsInstallKernel(ReadonlyVariable, KernelHelper):
class VariableOsInstallKernel(ReadonlyVariable,KernelHelper):
"""
Kernel filename
"""
def get(self):
bootdir = path.join(self.Get('cl_chroot_path'), 'boot')
modulesdir = path.join(self.Get('cl_chroot_path'), 'lib/modules')
bootdir = path.join(self.Get('cl_chroot_path'),'boot')
modulesdir = path.join(self.Get('cl_chroot_path'),'lib/modules')
validKernel = listDirectory(modulesdir)
kernelFiles = self.getFilesByType(bootdir, "Linux kernel")
kernelFiles = self.getFilesByType(bootdir,"Linux kernel")
installMarch = self.Get('os_install_arch_machine')
# kernelsWithVer = \
# list(map(lambda x: (
# x[0], (getTupleVersion("".join(x[1].groups()[0:3:2])),
# path.getmtime(x[0]))),
# # convert version to tuple( versionTuple, mtime)
# # version detect, for this version lib contains moudules
# # kernel arch equal install arch
# filter(lambda x: x[1] and x[1].group() in validKernel and
# installMarch in x[0].rpartition('/')[2],
# # (filename,version)
# map(lambda x: (x[0], self.reFindVer.search(x[1])),
# kernelFiles))))
kernelsWithVer = [(x[0],
(getTupleVersion("".join(x[1].groups()[0:3:2])),
path.getmtime(x[0]))) for x
# convert version to tuple( versionTuple, mtime)
# version detect, for this version lib contains moudules
# kernel arch equal install arch
in [y for y
# (filename,version)
in [(z[0], self.reFindVer.search(z[1])) for z in kernelFiles]
if y[1] and y[1].group() in validKernel and installMarch in y[0].rpartition('/')[2]]]
kernelsWithVer = \
map(lambda x:(x[0],(getTupleVersion("".join(x[1].groups()[0:3:2])),
path.getmtime(x[0]))),
# convert version to tuple( versionTuple, mtime)
# version detect, for this version lib contains moudules
# kernel arch equal install arch
ifilter(lambda x:x[1] and x[1].group() in validKernel and
installMarch in x[0].rpartition('/')[2],
# (filename,version)
imap(lambda x:(x[0],self.reFindVer.search(x[1])),
kernelFiles)))
if kernelsWithVer:
return path.split(max(kernelsWithVer, key=itemgetter(1))[0])[-1]
return path.split(max(kernelsWithVer,key=itemgetter(1))[0])[-1]
else:
return "vmlinuz"
class VariableOsInstallInitrd(ReadonlyVariable, KernelHelper):
class VariableOsInstallInitrd(ReadonlyVariable,KernelHelper):
"""
Optimized initramfs filename
"""
@ -431,20 +221,18 @@ class VariableOsInstallInitrd(ReadonlyVariable, KernelHelper):
self.Get('os_install_linux_shortname'),
self.Get('cl_chroot_path'),
self.Get('os_install_kernel'),
suffix="", notsuffix="-install") or \
suffix="",notsuffix="-install") or \
self.getInitrd(self.Get('os_install_arch_machine'),
self.Get('os_install_linux_shortname'),
self.Get('cl_chroot_path'),
self.Get('os_install_kernel'),
suffix="-install")[:-8] \
or "initrd"
or "initrd"
class VariableOsInstallInitrdInstall(ReadonlyVariable, KernelHelper):
class VariableOsInstallInitrdInstall(ReadonlyVariable,KernelHelper):
"""
Install initramfs filename
"""
def get(self):
return self.getInitrd(self.Get('os_install_arch_machine'),
self.Get('os_install_linux_shortname'),
@ -453,63 +241,43 @@ class VariableOsInstallInitrdInstall(ReadonlyVariable, KernelHelper):
suffix="-install") or "initrd-install"
class VariableOsInstallKernelConfig(ReadonlyVariable):
"""
Install config kernel filename
"""
value = ""
class VariableOsInstallSystemMap(ReadonlyVariable):
"""
Install system map filename
"""
def get(self):
systemmapfile = self.Get('os_install_kernel').replace('vmlinuz',
'System.map')
'System.map')
if systemmapfile.startswith('System.map') and path.exists(
path.join(self.Get('cl_chroot_path'), 'boot', systemmapfile)):
path.join(self.Get('cl_chroot_path'),'boot',systemmapfile)):
return systemmapfile
else:
return ""
class VariableOsInstallKernelCpufreq(ReadonlyVariable):
"""
Cpufreq modules
"""
def get(self):
"""Get cpufreq (and other from modules_3= param) from conf.d/modules"""
cpufreqmods = [x.partition('=')[2].strip("\n '\"") for x
in readLinesFile('/etc/conf.d/modules') if x.startswith('modules_3')]
cpufreqmods = map(lambda x:x.partition('=')[2].strip("\n '\""),
filter(lambda x:x.startswith('modules_3'),
readLinesFile('/etc/conf.d/modules')))
if cpufreqmods:
return cpufreqmods[0]
else:
return ""
class VariableClInstallKernelUid(ReadonlyVariable):
"""
Variable install kernel UID
"""
def get(self):
return getKernelUid(self.Get('os_install_root_dev'))
class VariableClInstallKernelBuild(Variable):
"""
Переменная используемся для GRP дистрибутивов и сборки нескольких ядер
"""
value = ""
class VariableClInstallKernelVersion(VariableOsInstallKernelConfig):
"""
Версия ядра в /usr/src/linux
"""
def get(self):
image = self.Get('cl_image')
if image:
with image:
try:
distrPath = image.getDirectory()
return self.get_kernel_src(distrPath)
except DistributiveError as e:
return ""
return ""

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -14,24 +14,25 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
from calculate.lib.datavars import ReadonlyVariable, VariableInterface
from calculate.lib.variables.linux import Linux
from os import path
from calculate.lib.datavars import Variable,VariableError,ReadonlyVariable
from calculate.lib.variables.linux import (Linux,VariableOsLinuxName,
VariableOsLinuxSystem,VariableOsLinuxSubname)
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
setLocalTranslate('cl_install3', sys.modules[__name__])
class InstallLinux(Linux, VariableInterface):
def __getFromImageOrCurrent(self, currentVar):
class InstallLinux(Linux):
def __getFromImageOrCurrent(self,currentVar):
"""Get value from install image or current system"""
if self.Get('cl_action') == 'system':
image = self.Get('cl_image')
if image:
d = image.getInfo()
# support lazy values
res = d.get(currentVar, "")
res = d.get(currentVar,"")
return str(res()) if callable(res) else res
else:
return ""
@ -47,55 +48,39 @@ class InstallLinux(Linux, VariableInterface):
"""Get by distroinfo or current info"""
return self.__getFromImageOrCurrent(self.current_variable)
class VariableOsInstallChrootableSet(InstallLinux, ReadonlyVariable):
"""Можно ли выполнить chroot в систему"""
current_variable = "os_chrootable_set"
class VariableOsChrootableSet(ReadonlyVariable):
"""Можно ли выполнить chroot в систему"""
type = "boolean"
value = "on"
class VariableOsInstallLinuxShortname(InstallLinux, ReadonlyVariable):
class VariableOsInstallLinuxShortname(InstallLinux,ReadonlyVariable):
"""Shortname of system"""
current_variable = "os_linux_shortname"
class VariableOsInstallLinuxVer(InstallLinux, ReadonlyVariable):
"""Version of system"""
class VariableOsInstallLinuxVer(InstallLinux,ReadonlyVariable):
"""Shortname of system"""
current_variable = "os_linux_ver"
class VariableOsInstallLinuxBuild(InstallLinux, ReadonlyVariable):
"""Build of system"""
class VariableOsInstallLinuxBuild(InstallLinux,ReadonlyVariable):
"""Shortname of system"""
current_variable = "os_linux_build"
class VariableOsInstallArchMachine(InstallLinux, ReadonlyVariable):
"""Arch of system"""
class VariableOsInstallArchMachine(InstallLinux,ReadonlyVariable):
"""Shortname of system"""
current_variable = "os_arch_machine"
class VariableOsInstallLinuxFiles(InstallLinux, ReadonlyVariable):
"""Files num in system"""
class VariableOsInstallLinuxFiles(InstallLinux,ReadonlyVariable):
"""Shortname of system"""
current_variable = "os_linux_files"
class VariableOsInstallLinuxName(InstallLinux, ReadonlyVariable):
class VariableOsInstallLinuxName(InstallLinux,ReadonlyVariable):
"""
Install distro name
"""
current_variable = "os_linux_name"
class VariableOsInstallLinuxSystem(InstallLinux, ReadonlyVariable):
class VariableOsInstallLinuxSystem(InstallLinux,ReadonlyVariable):
"""
Install system name
"""
current_variable = "os_linux_system"
class VariableOsInstallLinuxSubname(InstallLinux, ReadonlyVariable):
class VariableOsInstallLinuxSubname(InstallLinux,ReadonlyVariable):
"""
Install subname
"""

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -14,27 +14,24 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
from os import path
from calculate.lib.datavars import Variable, VariableError, ReadonlyVariable
from calculate.lib.variables.locale import Locale
from calculate.lib.utils.files import readLinesFile, process
from calculate.lib.utils.portage import isPkgInstalled
from calculate.lib.utils.common import (getValueFromCmdLine, getValueFromConfig,
CmdlineParams, cmpVersion)
from pytz import timezone, country_timezones, UnknownTimeZoneError
from calculate.lib.utils.common import getValueFromCmdLine, getValueFromConfig
from pytz import timezone,country_timezones,UnknownTimeZoneError
from datetime import datetime
from operator import itemgetter
from calculate.lib.cl_lang import setLocalTranslate, _
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
setLocalTranslate('cl_install3', sys.modules[__name__])
class LocaleVariable(ReadonlyVariable, Locale):
class LocaleVariable(ReadonlyVariable,Locale):
"""
Locale variables not using for flash installation
"""
def uncompatible(self):
"""
Network setting up unavailable for flash installation
@ -44,7 +41,6 @@ class LocaleVariable(ReadonlyVariable, Locale):
_("Locale configuration unavailable for Flash install")
return ""
class VariableOsInstallLinguas(LocaleVariable):
"""
Current LINGUAS value
@ -53,140 +49,111 @@ class VariableOsInstallLinguas(LocaleVariable):
def get(self):
def get_linguas(lines):
linguas = [x.strip().rpartition('=')[-1].strip('"\'') for x
in lines if x.startswith("LINGUAS=")]
linguas = map(lambda x:x.strip().rpartition('=')[-1].strip('"\''),
filter(lambda x: x.startswith("LINGUAS="),
lines))
return linguas[-1] if linguas else ""
makeconf = '/etc/make.conf'
emerge_config = self.Get('cl_emerge_config')
if emerge_config and "LINGUAS" in emerge_config:
return emerge_config['LINGUAS']
infocommand = ['emerge', '--info']
defaultLinguas = "bg en de es fr it pl pt_BR nl ru uk"
infocommand = ['emerge','--info']
defaultLinguas = "bg en de es fr it pl pt_BR ru uk"
# get linguas from make.conf, emerge --info or default
curlanguage = self.Get('os_install_locale_language')
return get_linguas(readLinesFile(makeconf)) or \
" ".join((x for x in get_linguas(process(*infocommand).readlines() or "").split() if x == "en" or x == curlanguage)) or defaultLinguas
" ".join(filter(lambda x:x=="en" or x==curlanguage,
get_linguas(
process(*infocommand).readlines() or "").split())) or \
defaultLinguas
class VariableOsInstallLocaleConsolefont(LocaleVariable):
"""
Consolefont for locale
"""
def get(self):
return self.getConsolefont(self.Get('os_install_locale_keyboard_layout'))
return self.getFieldByKeymap("consolefont",
self.Get('os_install_locale_keymap'))
class VariableOsInstallLocaleKeymap(LocaleVariable):
"""
Keymap of locale (used for /etc/conf.d/keymaps)
"""
def get(self):
return self.getKeymap(self.Get('os_install_locale_keyboard_layout'))
# get keymap from boot calculate param (keymap specified
# by lang)
keymapConfd = '/etc/conf.d/keymaps'
keymap = getValueFromCmdLine("calculate",1)
if self.isLangExists(keymap):
return self.getFieldByLang('keymap',keymap)
# get keymap by os_install_locale_lang
# Temporary comment get keymap from config file
#keymap = getValueFromConfig(keymapConfd,'KEYMAP')
#if keymap:
# return keymap
return self.getFieldByLang("keymap",
self.Get("os_install_locale_lang"))
class VariableOsInstallLocaleDumpkeys(LocaleVariable):
"""
Dumpkeys_charset for keymap
"""
def get(self):
# is specified keymap support by locale hash
if self.Get('os_install_locale_keymap') in self.getFields('keymap'):
return self.getDumpkeys_charset(
self.getKeyboardLayout(
keymap=self.Get('os_install_locale_keymap')))
return self.getFieldByKeymap("dumpkeys_charset",
self.Get('os_install_locale_keymap'))
else:
return self.getDumpkeys_charset(
self.Get('os_install_locale_keyboard_layout'))
return self.getFieldByLang("dumpkeys_charset",
self.Get('os_install_locale_lang'))
class VariableOsInstallLocaleLocale(LocaleVariable):
"""
Locale (at example: ru_RU.utf8)
Locale (at example: ru_RU.UTF-8)
"""
def get(self):
"""locale (example: ru_RU.utf8)"""
return self.getLocale(self.Get('os_install_locale_lang'))
"""locale (example: ru_RU.UTF-8)"""
return self.getFieldByLang("locale",
self.Get('os_install_locale_lang'))
class VariableOsInstallLocaleLang(LocaleVariable):
"""
Full language (at example: ru_RU)
"""
mode = 'w'
metavalue = "LOCALE"
metavalue = "LANG"
type = 'choice'
opt = ["--locale", "-l"]
opt = ["--lang","-l"]
def init(self):
self.label = _("Locale")
self.help = _("set the locale")
self.label = _("Language")
self.help = _("set the language")
def get(self):
"""lang (example: ru_RU)"""
return self.Get('os_locale_lang')
def choice(self):
return list(zip(self.Get('os_lang'),
map(str, self.Get('os_lang', humanreadable=True))))
class VariableOsInstallLocaleKeyboardLayout(LocaleVariable):
"""
Full language (at example: ru_RU)
"""
mode = 'w'
metavalue = "KEYMAP"
type = 'choice'
opt = ["--keymap", "-k"]
def init(self):
self.label = _("Keyboard layout")
self.help = _("set the keyboard layout")
def get(self):
"""lang (example: ru_RU)"""
selected_lang = self.Get('os_install_locale_lang')
current_lang = self.Get('os_locale_lang')
if selected_lang != current_lang:
return self.getKeyboardLayout(lang=self.Get('os_install_locale_lang'))
else:
return self.Get('os_locale_keyboard_layout')
def choice(self):
return list(zip(self.Get('os_keyboard_layout'),
map(str, self.Get('os_keyboard_layout', humanreadable=True))))
return sorted(zip(self.Get('os_lang'),
map(str,self.Get('os_lang',humanreadable=True))),key=itemgetter(1))
class VariableOsInstallLocaleLanguage(LocaleVariable):
"""
Short language (at example ru)
"""
def get(self):
return self.getLanguage(self.Get('os_install_locale_lang'))
return self.getFieldByLang("language",
self.Get('os_install_locale_lang'))
class VariableOsInstallLocaleXkb(LocaleVariable):
"""
Keyboard layout for X server
"""
def get(self):
return self.getXkblayout(self.Get('os_install_locale_keyboard_layout'))
return self.getFieldByLang("xkblayout",
self.Get('os_install_locale_lang'))
class VariableOsInstallLocaleXkbname(LocaleVariable):
"""
Keyboard layout name for X server
"""
def get(self):
localeXkb = self.Get("os_install_locale_xkb")
if localeXkb:
@ -202,7 +169,6 @@ class VariableOsInstallClockTimezone(LocaleVariable):
type = 'choiceedit'
metavalue = "TIMEZONE"
opt = ["--timezone"]
locale_varname = 'os_install_locale_lang'
def init(self):
self.label = _("Timezone")
@ -211,186 +177,154 @@ class VariableOsInstallClockTimezone(LocaleVariable):
def get(self):
return self.Get('os_clock_timezone')
def check(self, value):
def check(self,value):
if not value or not path.isfile(path.join(
"/usr/share/zoneinfo", value)):
raise VariableError(_("Wrong timezone %s") % value)
"/usr/share/zoneinfo",value)):
raise VariableError(_("Wrong timezone %s")%value)
def generateComments(self, tzs):
def generateComments(self,tzs):
"""
Generate comments by timezone names
"""
for tzname in tzs:
# add separator
if tzname == "---":
yield ("---", "---")
yield ("---","---")
continue
try:
tz = timezone(tzname)
strinfo = tz.localize(datetime.now()).strftime('%z')
yield (
tzname, "%s (%s:%s)" % (tzname, strinfo[:3], strinfo[-2:]))
yield (tzname,"%s (%s:%s)"%(tzname,strinfo[:3],strinfo[-2:]))
except UnknownTimeZoneError:
pass
def choice(self):
source = ["Etc/GMT-12",
"Pacific/Midway",
"Pacific/Honolulu",
"America/Anchorage",
"Canada/Pacific",
"America/Tijuana",
"America/Phoenix",
"America/Denver",
"America/Mazatlan",
"America/Monterrey",
"America/Regina",
"America/Mexico_City",
"Canada/Central",
"America/Bogota",
"America/New_York",
"America/Indiana/Indianapolis",
"America/Halifax",
"America/Caracas",
"America/Manaus",
"America/Santiago",
"America/St_Johns",
"America/Sao_Paulo",
"America/Argentina/Buenos_Aires",
"Etc/GMT+3",
"America/Montevideo",
"Atlantic/South_Georgia",
"Atlantic/Azores",
"Atlantic/Cape_Verde",
"UTC",
"Africa/Casablanca",
"Europe/Amsterdam",
"Europe/Belgrade",
"Europe/Brussels",
"Europe/Zagreb",
"Africa/Tunis",
"Europe/Kaliningrad",
"Asia/Amman",
"Europe/Athens",
"Europe/Istanbul",
"Asia/Beirut",
"Europe/Helsinki",
"Europe/Kiev",
"Europe/Sofia",
"Africa/Windhoek",
"Asia/Jerusalem",
"Africa/Cairo",
"Europe/Minsk",
"Africa/Harare",
"Europe/Moscow",
"Asia/Baghdad",
"Asia/Kuwait",
"Africa/Nairobi",
"Asia/Tbilisi",
"Asia/Tehran",
"Europe/Samara",
"Asia/Muscat",
"Asia/Baku",
"Asia/Yerevan",
"Asia/Kabul",
"Asia/Yekaterinburg",
"Asia/Karachi",
"Asia/Calcutta",
"Asia/Jayapura",
"Asia/Katmandu",
"Asia/Almaty",
"Asia/Omsk",
"Asia/Dhaka",
"Asia/Rangoon",
"Asia/Krasnoyarsk",
"Asia/Bangkok",
"Asia/Irkutsk",
"Asia/Hong_Kong",
"Asia/Singapore",
"Australia/Perth",
"Asia/Taipei",
"Asia/Yakutsk",
"Asia/Tokyo",
"Asia/Seoul",
"Australia/Adelaide",
"Australia/Darwin",
"Asia/Vladivostok",
"Australia/Brisbane",
"Pacific/Guam",
"Australia/Melbourne",
"Australia/Hobart",
"Asia/Srednekolymsk",
"Asia/Kamchatka",
"Pacific/Auckland",
"Etc/GMT-13"]
source = list(set(source + Locale().getFields('timezone')))
"Pacific/Midway",
"Pacific/Honolulu",
"America/Anchorage",
"Canada/Pacific",
"America/Tijuana",
"America/Phoenix",
"America/Denver",
"America/Mazatlan",
"America/Monterrey",
"America/Regina",
"America/Mexico_City",
"Canada/Central",
"America/Bogota",
"America/New_York",
"America/Indiana/Indianapolis",
"America/Halifax",
"America/Caracas",
"America/Manaus",
"America/Santiago",
"America/St_Johns",
"America/Sao_Paulo",
"America/Argentina/Buenos_Aires",
"Etc/GMT+3",
"America/Montevideo",
"Atlantic/South_Georgia",
"Atlantic/Azores",
"Atlantic/Cape_Verde",
"UTC",
"Africa/Casablanca",
"Europe/Amsterdam",
"Europe/Belgrade",
"Europe/Brussels",
"Europe/Zagreb",
"Africa/Tunis",
"Europe/Kaliningrad",
"Asia/Amman",
"Europe/Istanbul",
"Asia/Beirut",
"Europe/Helsinki",
"Europe/Kiev",
"Europa/Sofia",
"Africa/Windhoek",
"Asia/Jerusalem",
"Africa/Cairo",
"Europe/Minsk",
"Africa/Harare",
"Europe/Moscow",
"Asia/Baghdad",
"Asia/Kuwait",
"Africa/Nairobi",
"Asia/Tbilisi",
"Asia/Tehran",
"Europe/Samara",
"Asia/Muscat",
"Asia/Baku",
"Asia/Yerevan",
"Asia/Kabul",
"Asia/Yekaterinburg",
"Asia/Karachi",
"Asia/Calcutta",
"Asia/Jayapura",
"Asia/Katmandu",
"Asia/Almaty",
"Asia/Omsk",
"Asia/Dhaka",
"Asia/Rangoon",
"Asia/Krasnoyarsk",
"Asia/Bangkok",
"Asia/Irkutsk",
"Asia/Hong_Kong",
"Asia/Singapore",
"Australia/Perth",
"Asia/Taipei",
"Asia/Yakutsk",
"Asia/Tokyo",
"Asia/Seoul",
"Australia/Adelaide",
"Australia/Darwin",
"Asia/Vladivostok",
"Australia/Brisbane",
"Pacific/Guam",
"Australia/Melbourne",
"Australia/Hobart",
"Asia/Srednekolymsk",
"Asia/Kamchatka",
"Pacific/Auckland",
"Etc/GMT-13"]
def sortkey(s):
tz = timezone(s)
strinfo = tz.localize(datetime.now()).strftime('%z')
return int(strinfo[:3]), int("%s%s" % (strinfo[0], strinfo[-2:]))
return (int(strinfo[:3]),int("%s%s"%(strinfo[0],strinfo[-2:])))
try:
lang = self.Get(self.locale_varname).split('_')[1]
nativeTZ = [x for x in country_timezones[lang]]
lang = self.Get('os_install_locale_lang').split('_')[1]
nativeTZ = map(lambda x:x.encode('utf-8'),
country_timezones[lang])
source = nativeTZ + ["---"] + \
sorted([x for x in source if not x in nativeTZ], key=sortkey)
except (KeyError, IndexError) as e:
sorted(filter(lambda x:not x in nativeTZ,source),
key=sortkey)
except (KeyError,IndexError) as e:
pass
return list(self.generateComments(source))
class VariableOsInstallClockType(Variable):
"""
Type of clock (UTC or local)
"""
mode = 'w'
type = 'choice'
opt = ["--hwclock"]
metavalue = "CLOCK"
fallback_value = "local"
opt = ["--clocktype"]
metavalue = "CLOCKTYPE"
def init(self):
self.label = _("Hardware clock type")
self.help = _("set hardware clock type")
def exclude_value(self):
"""
Исключения
"""
root_type = self.Get('os_root_type')
hr_virtual = self.Get('hr_virtual')
# oracle virtualbox по умолчанию для linux систем выставляет
# использование UTC
if root_type == "livecd" and hr_virtual == "virtualbox":
return "UTC"
return None
self.label = _("Clock type")
def get(self):
"""type of clock (UTC or local)"""
# в первую очередь смотрим на параметры загрузки системы
cmdtype = getValueFromCmdLine(CmdlineParams.Calculate,
CmdlineParams.Clock)
if cmdtype and cmdtype in self.choice():
return cmdtype
# во вторую очередь исключения (например для livecd и virtualbox)
clocktype = self.exclude_value()
if clocktype:
return clocktype
# получаем значение из конфигурационных файлов hwclock
clockTypeFile = ['/etc/conf.d/clock', '/etc/conf.d/hwclock']
clockTypeFile = ['/etc/conf.d/clock','/etc/conf.d/hwclock']
for f in clockTypeFile:
clock = getValueFromConfig(f, "clock")
clock = getValueFromConfig(f,"clock")
if clock:
if clock.upper() == 'UTC':
return clock.upper()
elif clock.lower() == 'local':
return clock.lower()
# запасное значение
return self.fallback_value
return "local"
def choice(self):
return ["local", "UTC"]
return ["local","UTC"]

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2008-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -14,47 +14,52 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
from calculate.lib.datavars import (Variable, VariableInterface,
ReadonlyVariable, ReadonlyTableVariable,
FieldValue, HumanReadable)
from calculate.lib.utils import device
import re
import pty,fcntl
from subprocess import Popen
from os import path
from itertools import *
from calculate.lib.datavars import (TableVariable,Variable,VariableError,
ReadonlyVariable,ReadonlyTableVariable,
FieldValue)
from calculate.lib.utils.files import (process,checkUtils)
from calculate.install.distr import PartitionDistributive
from calculate.install.fs_manager import FileSystemManager
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
setLocalTranslate('cl_install3', sys.modules[__name__])
class LvmHelper(VariableInterface):
class LvmHelper:
def getLvmData(self):
for vg, lv, pv in device.lvm.pvdisplay_full():
yield lv, vg, pv
"""Get route table, exclude specifed iface"""
pvDisplayProg = checkUtils('/sbin/pvdisplay')
pvDisplay = process(pvDisplayProg,"--noh","-Co",
"lv_name,vg_name,pv_name")
for line in pvDisplay:
line = line.split()
if len(line) == 3:
yield line
#######################################################
# Devices variables
#######################################################
class VariableOsLvmData(ReadonlyTableVariable, LvmHelper):
class VariableOsLvmData(ReadonlyTableVariable,LvmHelper):
"""
Information about LVM
Information about disk devices
"""
source = ['os_lvm_lvname',
'os_lvm_vgname',
'os_lvm_pvname',
'os_lvm_pvname_parent'
]
'os_lvm_pvname']
def get(self, hr=HumanReadable.No):
def get(self,hr=False):
"""LVM hash"""
def generator():
for lvname, vgname, pvname in self.getLvmData():
all_base = device.udev.get_all_base_devices(name=pvname)
full_base = ",".join(all_base)
yield lvname, vgname, pvname, full_base
return list(generator()) or [[]]
return list(self.getLvmData()) or [[]]
setValue = Variable.setValue
class VariableOsLvmLvname(FieldValue, ReadonlyVariable):
class VariableOsLvmLvname(FieldValue,ReadonlyVariable):
"""
Logical volumes names
"""
@ -62,8 +67,7 @@ class VariableOsLvmLvname(FieldValue, ReadonlyVariable):
source_variable = "os_lvm_data"
column = 0
class VariableOsLvmVgname(FieldValue, ReadonlyVariable):
class VariableOsLvmVgname(FieldValue,ReadonlyVariable):
"""
Volume groups names
"""
@ -71,19 +75,10 @@ class VariableOsLvmVgname(FieldValue, ReadonlyVariable):
source_variable = "os_lvm_data"
column = 1
class VariableOsLvmPvname(FieldValue, ReadonlyVariable):
class VariableOsLvmPvname(FieldValue,ReadonlyVariable):
"""
Phisical volumes names
"""
type = "list"
source_variable = "os_lvm_data"
column = 2
class VariableOsLvmPvnameParent(FieldValue, ReadonlyVariable):
"""
Phisical volumes names
"""
type = "list"
source_variable = "os_lvm_data"
column = 3

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
#-*- coding: utf-8 -*-
# Copyright 2010-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2010-2013 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -14,413 +14,285 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import sys, time, os
from calculate.lib.datavars import VariableError, DataVarsError
from .distr import DistributiveError
from calculate.lib.datavars import VariableError,DataVarsError,DataVars
from calculate.install.install import InstallError
from calculate.install.distr import DistributiveError
from . import install
from calculate.lib.cl_lang import setLocalTranslate, getLazyLocalTranslate, _
setLocalTranslate('cl_install3', sys.modules[__name__])
import install
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
__ = getLazyLocalTranslate(_)
from calculate.core.server.func import WsdlBase
from calculate.lib.utils.partition import VolumesError
from .utils.cl_install import ClInstallAction
from .utils.cl_setup import (
ClSetupLocaleAction, ClSetupVideoAction, ClSetupSystemAction,
ClSetupBootAction, ClSetupNetworkAction, ClSetupAudioAction,
ClSetupSessionAction, ClSetupThemesAction)
from calculate.install.utils.cl_install import ClInstallAction
from calculate.install.utils.cl_setup import (ClSetupAudioAction,
ClSetupLocaleAction,ClSetupVideoAction,ClSetupSystemAction,
ClSetupBootAction,ClSetupNetworkAction,
ClSetupSessionAction)
class Wsdl(WsdlBase):
methods = [{
# идентификатор метода
'method_name': "install",
'method_name':"install",
# категория метода
'category': __("Installation"),
'category':__("Installation"),
# заголовок метода
'title': __("System Install"),
'title':__("System Install"),
# иконка для графической консоли
'image': ('calculate-install,system-installer,applications-other,'
'drive-harddisk'),
'image':'calculate-install,system-installer,applications-other,'\
'drive-harddisk',
# метод присутствует в графической консоли
'gui': True,
'gui':True,
# консольная команда
'command': 'cl-install',
'command':'cl-install',
# права для запуска метода
'rights': ['install'],
'rights':['install'],
# объект содержащий модули для действия
'logic': {'Install': install.Install},
'logic':{'Install':install.Install},
# описание действия
'action': ClInstallAction,
'action':ClInstallAction,
# объект переменных
'datavars': "install",
'native_error': (VariableError, DistributiveError, VolumesError,
DataVarsError, install.InstallError),
'datavars':"install",
'native_error':(VariableError,DistributiveError,
DataVarsError,install.InstallError),
# значения по умолчанию для переменных этого метода
'setvars': {'cl_action!': 'system',
'cl_chroot_status!': 'off', 'cl_install_type': 'hdd',
'cl_dispatch_conf': 'usenew'},
'setvars':{'cl_action!':'system','cl_dispatch_conf':'usenew'},
# описание груп (список лямбда функций)
'groups': [
lambda group: group(_("Language and locale"),
image="welcome",
normal=('os_install_locale_lang',
'os_install_clock_timezone'),
expert=('os_install_locale_keyboard_layout',
'os_install_clock_type',)),
lambda group: group(_("Distribution"),
normal=('cl_image_filename',),
hide=('cl_image_linux_shortname',
'cl_image_arch_machine',
'cl_image_new_only'),
expert=('cl_image_linux_shortname',
'cl_image_arch_machine',
'cl_image_new_only')),
lambda group: group(_("Installation type"),
normal=('cl_autopartition_set',),
hide=('cl_autopartition_set',
'cl_autopartition_root_size',
'cl_autopartition_root_format',
'cl_autopartition_calculate_format',
'cl_autopartition_swap_size',),
brief=('cl_autopartition_brief_set',),
expert=('cl_autopartition_scheme',
'cl_autopartition_root_format',
'cl_autopartition_calculate_format',
'cl_autopartition_table',
'cl_autopartition_root_size',
'cl_autopartition_swap_size',
'cl_autopartition_device'),
expert_label=_(
"Click to select partitions to be created")
),
lambda group: group(_("Layout"),
normal=('os_location_data',),
hide=('os_location_data', 'os_install_mbr',
'os_install_uefi'),
brief_force=('os_location_brief_data',
'os_install_bootloader'),
brief=('os_install_uefi',),
expert=('cl_uuid_set',
'os_install_mbr',
'os_install_uefi')),
lambda group: group(_("Network settings"),
normal=(
'cl_network_migrate_set',),
expert=('os_install_net_conf',
'os_install_net_data',
'os_install_net_fqdn', 'os_install_ntp',
'os_install_net_dns',
'os_install_net_dns_search',
'os_install_net_route_data'),
expert_label=_(
"Click to select network settings")
),
lambda group: group(_("Users"),
normal=(
'cl_migrate_root_pwd_plain',
'cl_grub_passwd_set',
'cl_migrate_data',
'cl_autologin'),
expert=('cl_install_home_crypt_set',),
hide=('cl_migrate_data',),
brief=('cl_migrate_data_brief',)),
lambda group: group(_("Audio"),
normal=('os_audio',),
expert=('os_audio_default',)),
lambda group: group(_("Video"),
normal=('os_install_x11_video_drv',
'os_install_x11_composite',
'os_install_x11_resolution_preferred',
'os_install_grub_terminal'),
expert=('os_install_fb_resolution_preferred',)),
lambda group:group(_("Language and locale"),
image="welcome",
normal=('os_install_locale_lang','os_install_clock_timezone')),
lambda group:group(_("Distribution"),
normal=('cl_image_filename',),
hide=('cl_image_linux_shortname','cl_image_arch_machine',
'cl_image_new_only'),
expert=('cl_image_linux_shortname', 'cl_image_arch_machine',
'cl_image_new_only')),
lambda group:group(_("Allocate drive space"),
normal=('cl_autopartition_set',),
expert=('cl_autopartition_scheme',
'cl_autopartition_table','cl_autopartition_root_size',
'cl_autopartition_swap_size',
'cl_autopartition_device'),
expert_label=_("Click to set up autopartition options")),
lambda group:group(_("Mount points"),
normal=('os_location_data',),
hide=('os_location_data','os_install_mbr','os_install_uefi_set'),
brief_force=('os_location_brief_data','os_install_bootloader',
'os_install_uefi_set'),
expert=('cl_uuid_set',
'os_install_root_type',
'os_install_mbr',
'os_install_uefi_set',
'os_install_kernel_scheduler')),
lambda group:group(_("Network settings"),
normal=('os_install_net_conf','os_install_net_data',
'os_install_net_fqdn','os_install_ntp'),
expert=('os_install_net_dns','os_install_net_dns_search',
'os_install_net_route_data')),
lambda group:group(_("Users"),
normal=('cl_migrate_root_pwd','cl_migrate_data','cl_autologin'),
expert=('cl_install_home_crypt_set',),
hide=('cl_migrate_data',),
brief=('cl_migrate_data_brief',)),
lambda group:group(_("Video"),
normal=('os_install_x11_video_drv','os_install_x11_composite',
'os_install_x11_resolution','os_install_fb_resolution',
'os_install_grub_terminal')),
lambda group: group(_("Update"),
normal=('cl_install_autocheck_set',
'cl_install_autocheck_interval',
'cl_install_cleanpkg_set',
'cl_install_other_set'),
expert=('cl_install_update_pkg_set',))],
# действие выводит информацию перед запуском
'brief': {'next': __("Run"),
'image': 'finish',
'name': __("Start installing")}},
normal=('cl_install_autocheck_set',
'cl_install_autocheck_interval',
'cl_install_cleanpkg_set',
'cl_install_other_set'))],
# действие выводит информацию перед запуском
'brief':{'next':__("Perform"),
'image':'finish',
'name':__("Start installing")}},
# установка на Flash
{
'method_name': "install_flash",
'category': __("Installation"),
'title': __("Flash Install"),
'image': ('calculate-install-flash,'
'drive-removable-media-usb-pendrive,'
'drive-removable-media-usb,media-flash'),
'command': 'cl-install-flash',
'gui': True,
'rights': ['install'],
'logic': {'Install': install.Install},
'action': ClInstallAction,
'datavars': "install",
'native_error': (VariableError, DistributiveError, VolumesError,
DataVarsError, install.InstallError),
'setvars': {'cl_action!': 'system',
'cl_chroot_status!': 'off',
'cl_install_type': 'flash',
'cl_protect_use_set!': 'off',
'cl_autopartition_set!': 'off',
'cl_dispatch_conf': 'usenew'},
'groups': [
lambda group: group(_("Flash install"),
normal=('cl_image_filename',
'os_install_disk_single',
'cl_target_fs',
'os_install_format_single_set'),
next_label=_("Run"))],
'brief': {'next': __("Run"),
'name': __("Start installing")}},
'method_name': "install_flash",
'category': __("Installation"),
'title': __("Flash Install"),
'image': ('drive-removable-media-usb-pendrive,'
'drive-removable-media-usb,media-flash'),
'gui':True,
'rights':['install'],
'logic':{'Install':install.Install},
'action':ClInstallAction,
'datavars':"install",
'native_error':(VariableError,DistributiveError,
DataVarsError,install.InstallError),
'setvars':{'cl_action!':'system','cl_install_type':'flash',
'cl_protect_use_set!':'off',
'cl_dispatch_conf':'usenew'},
'groups':[
lambda group:group(_("Flash install"),
normal=('os_install_disk_single','cl_image_filename'),
expert=('os_location_data',),
next_label=_("Perform"))]},
# PXE установка
{
'method_name': "install_pxe",
'category': __("Installation"),
'title': __("PXE Install"),
'image': ('calculate-install-pxe,gnome-network-properties,'
'network-server,'
'preferences-desktop-remote-desktop'),
'command': 'cl-install-pxe',
'gui': True,
'rights': ['installpxe'],
'logic': {'Install': install.Install},
'action': ClInstallAction,
'datavars': "install",
'native_error': (VariableError, DistributiveError,
DataVarsError, install.InstallError),
'setvars': {'cl_action!': 'system', 'os_install_pxe': 'on',
'cl_protect_use_set!': 'off',
'cl_dispatch_conf': 'usenew'},
# действие выводит информацию перед запуском
'brief': {'next': __("Installation"),
'image': 'finish',
'name': __("Start installing")},
'groups': [
lambda group: group(_("PXE install"),
normal=('cl_image_filename',),
expert=('os_install_pxe_path',
'os_install_pxe_ip'),
next_label=_("Run"))]},
'method_name':"install_pxe",
'category':__("Installation"),
'title':__("PXE Install"),
'image':('gnome-network-properties,network-server,'
'preferences-desktop-remote-desktop'),
'command':'cl-install-pxe',
'gui':True,
'rights':['installpxe'],
'logic':{'Install':install.Install},
'action':ClInstallAction,
'datavars':"install",
'native_error':(VariableError,DistributiveError,
DataVarsError,install.InstallError),
'setvars':{'cl_action!':'system','os_install_pxe':'on',
'cl_protect_use_set!':'off',
'cl_dispatch_conf':'usenew'},
# действие выводит информацию перед запуском
'brief':{'next':__("Installation"),
'image':'finish',
'name':__("Start installing")},
'groups':[
lambda group:group(_("PXE install"),
normal=('cl_image_filename',),
expert=('os_install_pxe_path',
'os_install_pxe_ip'),
next_label=_("Perform"))]},
# настройка загрузки системы
{
'method_name': "setup_boot",
'category': __("Configuration"),
'title': __("Boot"),
'image': 'calculate-setup-boot,stock_save,drive-harddisk',
'command': 'cl-setup-boot',
'gui': True,
'rights': ['setupboot'],
'logic': {'Install': install.Install},
'action': ClSetupBootAction,
'datavars': "install",
'native_error': (
VariableError, DataVarsError, install.InstallError),
'setvars': {'cl_action!': 'merge', 'cl_merge_pkg!': [None],
'cl_merge_set!': "on", 'cl_setup': 'boot'},
'groups': [
lambda group: group(_("Boot"),
normal=(
'os_install_mbr',
'os_install_uefi',
'os_install_grub_terminal',
'cl_grub_pwd',
'cl_grub_remove_pwd_set',
),
expert=(
'cl_templates_locate',
'cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
{
# настройка сети
'method_name': "setup_network",
'category': __("Configuration"),
'title': __("Network"),
'image': 'calculate-setup-network,network-workgroup,'
'network-idle,preferences-system-network',
'command': 'cl-setup-network',
'gui': True,
'rights': ['setupnetwork'],
'logic': {'Install': install.Install},
'action': ClSetupNetworkAction,
'datavars': "install",
'native_error': (
VariableError, DataVarsError, install.InstallError),
'setvars': {'cl_action!': 'merge', 'cl_merge_pkg!': [None],
'cl_network_migrate_set': 'off',
'cl_merge_set!': "on", 'cl_setup': 'network'},
'groups': [
lambda group: group(_("Network"),
normal=('os_install_net_conf',
'os_install_net_data',
'os_install_net_fqdn',
'os_install_ntp'),
expert=('os_install_net_dns',
'os_install_net_dns_search',
'os_install_net_route_data',
'cl_templates_locate',
'cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
{
# перенастройка системы
'method_name': "setup_system",
'category': __("Configuration"),
'title': __("System"),
'image': 'calculate-setup-system,run-build,applications-ide,'
'system-run,system,computer',
'command': 'cl-setup-system',
'gui': True,
'rights': ['setupsystem'],
'logic': {'Install': install.Install},
'action': ClSetupSystemAction,
'datavars': "install",
'native_error': (
VariableError, DataVarsError, install.InstallError),
'setvars': {'cl_action!': 'merge', 'cl_live': 'off'},
'groups': [
lambda group: group(_("Update system settings"),
normal=('cl_live',
'cl_network_configure_set'),
expert=(
'cl_templates_locate',
'cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
'method_name':"setup_boot",
'category':__("Configuration"),
'title':__("Boot"),
'image':'stock_save,drive-harddisk',
'command':'cl-setup-boot',
'gui':True,
'rights':['setupboot'],
'logic':{'Install':install.Install},
'action':ClSetupBootAction,
'datavars':"install",
'native_error':(VariableError,DataVarsError,install.InstallError),
'setvars':{'cl_action!':'merge','cl_merge_pkg!':[None],
'cl_merge_set!':"on",'cl_setup':'boot'},
'groups':[
lambda group:group(_("Boot"),
normal=('os_install_mbr','os_install_uefi_set',
'os_install_kernel_scheduler',
'os_install_grub_terminal'),
expert=('cl_templates_locate','cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
{
# настройка видео
'method_name': "setup_video",
'category': __("Configuration"),
'title': __("Video"),
'image': 'calculate-setup-video,system-config-display,'
'video-display,gnome-multimedia',
'command': 'cl-setup-video',
'gui': True,
'rights': ['setupvideo'],
'logic': {'Install': install.Install},
'action': ClSetupVideoAction,
'datavars': "install",
'native_error': (
VariableError, DataVarsError, install.InstallError),
'setvars': {'cl_action!': 'merge', 'cl_merge_pkg!': [None],
'cl_merge_set!': "on", 'cl_setup': 'video'},
'groups': [
lambda group: group(
_("Video"),
normal=('os_install_x11_video_drv',
'os_install_x11_resolution_preferred',
'os_install_x11_composite'),
expert=(
'os_install_fb_resolution_preferred',
'cl_templates_locate',
'cl_dispatch_conf',
# настройка сети
'method_name':"setup_network",
'category':__("Configuration"),
'title':__("Network"),
'image':'network-workgroup,'
'network-idle,preferences-system-network',
'command':'cl-setup-network',
'gui':True,
'rights':['setupnetwork'],
'logic':{'Install':install.Install},
'action':ClSetupNetworkAction,
'datavars':"install",
'native_error':(VariableError,DataVarsError,install.InstallError),
'setvars':{'cl_action!':'merge','cl_merge_pkg!':[None],
'cl_merge_set!':"on",'cl_setup':'network'},
'groups':[
lambda group:group(_("Network"),
normal=('os_install_net_conf','os_install_net_data',
'os_install_net_fqdn','os_install_ntp'),
expert=('os_install_net_dns','os_install_net_dns_search',
'os_install_net_route_data',
'cl_templates_locate','cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
next_label=_("Save"))]},
{
# настройка звука
'method_name': "setup_audio",
'category': __("Configuration"),
'title': __("Audio"),
'image': 'calculate-setup-audio,audio-card',
'command': 'cl-setup-audio',
'gui': True,
'rights': ['setupaudio'],
'logic': {'Install': install.Install},
'action': ClSetupAudioAction,
'datavars': "install",
'native_error': (
VariableError, DataVarsError, install.InstallError),
'setvars': {'cl_action!': 'merge', 'cl_merge_pkg!': [None],
'cl_merge_set!': "on", 'cl_setup': 'audio'},
'groups': [
lambda group: group(_("Audio"),
normal=('os_audio',),
expert=(
'os_audio_default',
'cl_templates_locate',
'cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
# перенастройка системы
'method_name':"setup_system",
'category':__("Configuration"),
'title':__("System"),
'image':'applications-ide,system-run,system,computer',
'command':'cl-setup-system',
'gui':True,
'rights':['setupsystem'],
'logic':{'Install':install.Install},
'action':ClSetupSystemAction,
'datavars':"install",
'native_error':(VariableError,DataVarsError,install.InstallError),
'setvars':{'cl_action!':'merge','cl_live':'off'},
'groups':[
lambda group:group(_("Update system settings"),
normal=('cl_live',),
expert=('cl_templates_locate','cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
{
# настройка локали
'method_name': "setup_locale",
'category': __("Configuration"),
'title': __("Locale"),
'image': 'calculate-setup-locale,locale,preferences-desktop-locale',
'command': 'cl-setup-locale',
'gui': True,
'rights': ['setuplocale'],
'logic': {'Install': install.Install},
'action': ClSetupLocaleAction,
'datavars': "install",
'native_error': (
VariableError, DataVarsError, install.InstallError),
'setvars': {'cl_action!': 'merge', 'cl_merge_pkg!': [None],
'cl_merge_set!': "on", 'cl_setup': 'locale'},
'groups': [
lambda group: group(_("Locale"),
normal=('os_install_locale_lang',
'os_install_clock_timezone'),
expert=(
'os_install_locale_keyboard_layout',
'os_install_clock_type',
'cl_templates_locate',
'cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
# настройка видео
'method_name':"setup_video",
'category':__("Configuration"),
'title':__("Video"),
'image':'system-config-display,video-display,gnome-multimedia',
'command':'cl-setup-video',
'gui':True,
'rights':['setupvideo'],
'logic':{'Install':install.Install},
'action':ClSetupVideoAction,
'datavars':"install",
'native_error':(VariableError,DataVarsError,install.InstallError),
'setvars':{'cl_action!':'merge','cl_merge_pkg!':[None],
'cl_merge_set!':"on",'cl_setup':'video'},
'groups':[
lambda group:group(_("Video"),
normal=('os_install_x11_video_drv',
'os_install_x11_resolution',
'os_install_x11_composite',
'os_install_fb_resolution'),
expert=('cl_templates_locate','cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
{
# настройка локали
'method_name': "setup_session",
'category': __("Configuration"),
'title': __("Session"),
'image': 'calculate-setup-session,system-lock-screen',
'command': 'cl-setup-session',
'gui': True,
'rights': ['setupsession'],
'logic': {'Install': install.Install},
'action': ClSetupSessionAction,
'datavars': "install",
'native_error': (
VariableError, DataVarsError, install.InstallError),
'setvars': {'cl_action!': 'merge', 'cl_merge_pkg!': [None],
'cl_merge_set!': "on", 'cl_setup': 'session'},
'groups': [
lambda group: group(_("Session"),
normal=('cl_autologin',
'cl_install_home_crypt_set'),
expert=(
'cl_templates_locate',
'cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
# настройка локали
'method_name':"setup_locale",
'category':__("Configuration"),
'title':__("Locale"),
'image':'locale,preferences-desktop-locale',
'command':'cl-setup-locale',
'gui':True,
'rights':['setuplocale'],
'logic':{'Install':install.Install},
'action':ClSetupLocaleAction,
'datavars':"install",
'native_error':(VariableError,DataVarsError,install.InstallError),
'setvars':{'cl_action!':'merge','cl_merge_pkg!':[None],
'cl_merge_set!':"on",'cl_setup':'locale'},
'groups':[
lambda group:group(_("Locale"),
normal=('os_install_locale_lang',
'os_install_clock_timezone'),
expert=('cl_templates_locate','cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]},
{
# настройка тем
'method_name': "setup_theme",
'category': None,
'title': __("Themes"),
'image': None,
'command': 'cl-setup-themes',
'gui': True,
'rights': ['setupthemes'],
'logic': {'Install': install.Install},
'action': ClSetupThemesAction,
'datavars': "install",
'native_error': (
VariableError, DataVarsError, install.InstallError),
'setvars': {'cl_action!': 'merge', 'cl_merge_pkg!': [None],
'cl_merge_set!': "on", 'cl_setup': 'themes'},
'groups': [
lambda group: group(_("Session"),
normal=(),
expert=(
'cl_templates_locate',
'cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]}
]
# настройка локали
'method_name':"setup_session",
'category':__("Configuration"),
'title':__("Session"),
'image':'session-properties',
'command':'cl-setup-session',
'gui':True,
'rights':['setupsession'],
'logic':{'Install':install.Install},
'action':ClSetupSessionAction,
'datavars':"install",
'native_error':(VariableError,DataVarsError,install.InstallError),
'setvars':{'cl_action!':'merge','cl_merge_pkg!':[None],
'cl_merge_set!':"on",'cl_setup':'session'},
'groups':[
lambda group:group(_("Session"),
normal=('cl_autologin', 'cl_install_home_crypt_set'),
expert=('cl_templates_locate','cl_dispatch_conf',
'cl_verbose_set'),
next_label=_("Save"))]}
]

@ -3,7 +3,7 @@
# setup.py --- Setup script for calculate-install
# Copyright 2010-2016 Mir Calculate. http://www.calculate-linux.org
# Copyright 2010 Calculate Ltd. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
@ -23,61 +23,20 @@ __version__ = '3.2.2'
import os
import stat
from distutils.core import setup, Extension
from calculate.install_data import install_data
from os import system,path
import glob
import sys
from distutils.command import install_data as module_install_data
from distutils.util import change_root, convert_path
class install_data(module_install_data.install_data):
def run (self):
self.mkpath(self.install_dir)
for f in self.data_files:
if isinstance(f, str):
# it's a simple file, so copy it
f = convert_path(f)
if self.warn_dir:
self.warn("setup script did not provide a directory for "
"'%s' -- installing right in '%s'" %
(f, self.install_dir))
(out, _) = self.copy_file(f, self.install_dir)
self.outfiles.append(out)
else:
# it's a tuple with path to install to and a list of files
dir = convert_path(f[0])
if not os.path.isabs(dir):
dir = os.path.join(self.install_dir, dir)
elif self.root:
dir = change_root(self.root, dir)
self.mkpath(dir)
if f[1] == []:
# If there are no files listed, the user must be
# trying to create an empty directory, so add the
# directory to the list of output files.
self.outfiles.append(dir)
else:
# Copy files, adding them to the list of output files.
for data in f[1]:
# is's a simple filename without chmod
if isinstance(data,str):
chmod = None
else:
data, chmod = data
data = convert_path(data)
(out, _) = self.copy_file(data, dir)
if chmod and os.stat(out).st_mode != chmod:
os.chmod(out,chmod)
self.outfiles.append(out)
data_files = []
data_files += [('/etc/init.d', [('data/calculate',0o755)]),
('/usr/bin',[('bin/xautologin',0o755)]),
data_files += [('/etc/init.d', [('data/calculate',0755)]),
('/usr/bin',[('bin/xautologin',0755)]),
('/usr/share/calculate/doc', ['data/handbook-en.html',
'data/handbook-ru.html']),
('/usr/libexec/calculate', [('data/cl-video-install', 0o755)]),
('/bin',[('bin/bashlogin',0o755)])]
'data/handbook-ru.html',
'data/handbook-es.html',
'data/handbook-fr.html']),
('/bin',[('bin/bashlogin',0755)])]
packages = [
"calculate."+str('.'.join(root.split(os.sep)[1:]))

Loading…
Cancel
Save