Compare commits

...

379 Commits

Author SHA1 Message Date
Павел Иванов df262fa4d5 fix: Установка UEFI
3 months ago
Павел Иванов 210b51ee82 TG-532 fix PXE install
3 months ago
Павел Иванов 724985edb4 TG-392 Установка в раздел EFI
8 months ago
Павел Иванов ecac76290b TG-392 Установка системы на раздел EFI
8 months ago
root 40c800dc00 TG-230
1 year ago
root 397ac25381 Удаление 686
1 year ago
root 3e7f20f4ce TG-199
1 year ago
root d9c5771203 TG-195
1 year ago
root cdd9fbd751 TG-195
1 year ago
root f9ebdb892b Fix: изменение текста ненадежного пароля
1 year ago
root bd7a6e1973 TG-195
1 year ago
root e05cf14133 TG-174
1 year ago
root 45289a8516 TG-121
1 year ago
root ef5d75f040 Merge branch 'master' of https://git.calculate-linux.org/calculate/calculate-utils-3-install
1 year ago
root 0882d2e27b TG-121
1 year ago
Alexander Tratsevskiy a92d5a7d02 Update live handbook
1 year ago
root 0dabba6a6e TG-4
1 year ago
root 4330087bf3 Feature: fglrx removed from default list
1 year ago
Павел Иванов 47cfc98f11 Добавлена поддерка нового пути к портежам
2 years ago
Павел Иванов 35bb751fb5 Удалено условие выбора директории портежей
2 years ago
Павел Иванов 148f26ba66 Перенос /usr/portage в /var/db/repos/gentoo
2 years ago
Павел Иванов c0e1c32534 Fix: nvidia 470 booting
2 years ago
idziubenko fcab4a2780 added error case to installFbResolution
2 years ago
idziubenko 90c9d3dfd0 fixed server bootstrap on livecd
2 years ago
Alexander Tratsevskiy f471b47479 Do not configure calculate server on the first booting from the lxc
2 years ago
idziubenko 8936df0cf5 Fix: added /run to mounted dirs (builder)
2 years ago
idziubenko 2747fe8077 FIX: removed space_cache from btrfs fstab
2 years ago
idziubenko 49350af92d FIX: added exception when utilities can't get MType of iso
2 years ago
idziubenko 1a790afba7 FEAT: added local to depend for init.d/calculate
2 years ago
idziubenko 4528551f32 FEAT: cl-install now migrates machine-id
2 years ago
idziubenko c3c87d13ef added system error code for failed install due to build already present
2 years ago
idziubenko 77aea752b4 added exception for .old files in .ssh
2 years ago
idziubenko 8e8453f725 reverted ext4 fast_commit
3 years ago
idziubenko f97577dc16 Merge branch 'master' of git.calculate-linux.org:calculate/calculate-utils-3-install
3 years ago
idziubenko 32ed578925 added ext4 fast_commit option
3 years ago
Alexander Tratsevskiy ed525321e0 Removed discard mount option
3 years ago
idziubenko 9aeab9e184 fixed cl-video-install newline return
3 years ago
idzuibenko c6de0c9ec8 swapped PulseAudio for PipeWire
3 years ago
idzuibenko 7bd8f1bf17 removed undefined variable from nvidia get_legacy
3 years ago
idzuibenko 01cd79f702 fixed ip routes, removed maps
3 years ago
idzuibenko 7965493b9b loading bar now limited to 100%
3 years ago
Иван Дзюбенко fb8b83bdf4 fixed extcomparator
3 years ago
Иван Дзюбенко 6ef7e912f3 fixed zip related bugs (notably in install grub uefi)
3 years ago
Иван Дзюбенко b5993c5616 fixed encoding in timezone variables
3 years ago
idziubenko 53c76fde3a fixed build compare
3 years ago
idziubenko dcc9cb852d fixed cl-install flash
3 years ago
idziubenko 667112d919 fixed pipe encoding
3 years ago
idziubenko 9cda6d8384 fixed migrate users
3 years ago
idziubenko 4a14d64240 fixed division operations
3 years ago
idziubenko 1b187a1844 fixed clImagePath
3 years ago
idziubenko 9a2462c120 fixed hashing
3 years ago
idziubenko 49f760d3ee imports to relative
3 years ago
idziubenko b23b15293a Merge branch 'py3_forced'
3 years ago
idziubenko f30a4133f0 general py3 changes, regex fixes
3 years ago
idziubenko 57df4358f0 fixed old sorting function, modernized classes
3 years ago
idziubenko 545a3a583c added more list compr, general py3 changes
3 years ago
idziubenko aa3120cec2 replaced filters/maps with list comprehensions
3 years ago
idziubenko 072415613f more datavars fixes
3 years ago
idziubenko b1a5dc6e64 Py3 changes
3 years ago
Хирецкий Михаил 359e71ccae Fix setup.py
3 years ago
idziubenko 409534d108 i
3 years ago
Хирецкий Михаил d8c14903e9 Добавлена маскировка nvidia-drivers через calculate/ini.env
3 years ago
Хирецкий Михаил ad9a1a1cc9 Изменена настройка alsa volume
3 years ago
Хирецкий Михаил 9a85da3620 Добавлена поддержка f2fs
3 years ago
Хирецкий Михаил db3766eaa2 Исправлен выбор групп на CSS
3 years ago
Хирецкий Михаил 031a92dc28 Remove xdm before init.d/calculate
3 years ago
Хирецкий Михаил b686761529 Исправлено прописывание маски nvidia при первой загрузке
3 years ago
Хирецкий Михаил 8a79c02363 Изменён приоритет при определении текущего видеодрайвера
3 years ago
Хирецкий Михаил 0d2de67f8e Исправлена последовательность запуска (после display-manager)
3 years ago
Хирецкий Михаил d3440bc46d Добавлена переменная предпочтения файловых систем, предпочитаемой файловой системой назначена Btrfs
3 years ago
Хирецкий Михаил 5f9cd36e2d Добавлена возможность указывать степень сжатия btrfs через переменную
3 years ago
Хирецкий Михаил 144ca153cd Исправлена маскировка nvidia-drivers в зависимости от ID карты
3 years ago
Хирецкий Михаил e62d86880c Изменена установка на btrfs с сжатием
3 years ago
Хирецкий Михаил fc2e151e92 Добавлен часовой пояс Europe/Athens
3 years ago
Хирецкий Михаил 182b67f61c Добавлено округление при проверке размера bios_boot (2)
3 years ago
Хирецкий Михаил 227eb8a9fc Добавлено округление при проверке размера bios_boot
3 years ago
Хирецкий Михаил b960214b41 Исправлена ошибка сообщающая о примонтировании устройства без названия.
3 years ago
Хирецкий Михаил 2bb1d2a559 Исправлено вычисление переменных Kernel
3 years ago
Хирецкий Михаил 0b621dd63d Удалена настройка OpenGL через "eselect opengl"
3 years ago
Хирецкий Михаил 53e42d8282 Добавлена возможность выбора nvidia драйвера
3 years ago
Хирецкий Михаил c9bfd00424 Исправлено использование swap раздела для гибернации
3 years ago
Хирецкий Михаил 3c6df3681a Исправлено монтирование многослойной файловой системы при сборке
3 years ago
Хирецкий Михаил 6aaa79f03a Добавлена переменная cl_install_scaling, для указания hi, как увеличенного размера интерфейса
4 years ago
Хирецкий Михаил 0ed841e079 Add EDID variables and DPI
4 years ago
Хирецкий Михаил 377f714b9d Исправлена опечатка в handbook
4 years ago
Хирецкий Михаил 2f64c6a65f Добавлена попытка отключения устройств на которые будет ставиться система если используется параметр --force
4 years ago
Хирецкий Михаил 8787048376 Добавлена проверка на примонтированные разделы диска используемого для авторазметки
4 years ago
Хирецкий Михаил ba8c6fd336 Исправлена неправильное описание ошибки при попытке выбрать DOS таблицу и UEFI
4 years ago
Хирецкий Михаил e806d8e3a8 Исправлено разворачивание сборки на flash дистрибутивах
4 years ago
Хирецкий Михаил e6fcfca66a Remove swap partition for autopartition by default.
4 years ago
Хирецкий Михаил 3eb455e8dd Исправлена установка nvidia во время загрузки системы
4 years ago
Хирецкий Михаил a6e33a1357 PulseAudio по умолчанию
4 years ago
Хирецкий Михаил ab6b6d60a7 Добавлена возможность выбрать vesa драйвер из списка --video
4 years ago
Хирецкий Михаил c0b561bd13 lpadmin добавлен в список групп по умолчанию
4 years ago
Хирецкий Михаил 618d3a6d1e Исправлена установка PXE, и настройка live PXE
4 years ago
Хирецкий Михаил fcab3a6529 Добавлено сообщение "no" если загрузчик не устанавливается
4 years ago
Хирецкий Михаил 21cb6ac55b Добавлен перенос параметра загрузки ядра nomodeset
4 years ago
Хирецкий Михаил 9389352c6e Добавлена проверка наличия утилиты форматирования при выборе файловой системы для авторазметки
4 years ago
Хирецкий Михаил a088646cd1 Добавлено обновление списка правил для udev во вермя init.d/calculate
4 years ago
Хирецкий Михаил e9f463d419 Убрана wheel группа из списка по умолчанию
4 years ago
Хирецкий Михаил b4481e9d06 Добавлена переменная ac_install_config
4 years ago
Хирецкий Михаил e458e974f5 Добавлена переменная для определения типа MAC адреса
4 years ago
Хирецкий Михаил 57f32415b5 Добавлена переменная для определения типа сетевого интерфейса eth или wlan
4 years ago
Хирецкий Михаил b14ab8b647 Изменено вычисление значения по умолчанию для параметра "-D"
4 years ago
Хирецкий Михаил 79a4b7fb0b Add python and lib variables
4 years ago
Хирецкий Михаил 415845d370 --calculate-fs -> --data-fs
5 years ago
Хирецкий Михаил aff13dbe8f Добавлена возможность выборка modesetting видеодрайвера
5 years ago
Хирецкий Михаил b907d2c099 Добавлена поддержка Gentoo профиля 17.1
5 years ago
Хирецкий Михаил 9f14bb48e0 Изменено сообщение при необходимости ввести пароль пользователя
5 years ago
Хирецкий Михаил a7ac43c132 Добавлена возможность выбора разрешения FB
5 years ago
Хирецкий Михаил 5cf9f16ad6 Calculate раздел переименован в "Раздел для данных"
5 years ago
Хирецкий Михаил 749af0fdca Добавлена проверка на своп нулевого размера
5 years ago
Хирецкий Михаил b713311583 Изменён минимальный размер раздела BIOS boot
5 years ago
Хирецкий Михаил 226c4636bd Для переменной cl_splash_image_hash добавлен учёт изменений plymouth
5 years ago
Хирецкий Михаил 003ff5d128 Добавлен параметр для установки системы для обновления пакетов при первой загрузке
5 years ago
Хирецкий Михаил 4aaf71035e Исправлен импорт модуля
5 years ago
Хирецкий Михаил 2ca357b2c9 Исправлено использование уже отформатированных разделов
5 years ago
Хирецкий Михаил 420b9b27b2 Добавлена возможность выбора файловой системы для корня и данных при авторазметке
5 years ago
Хирецкий Михаил eeb361db80 Рефакторинг: работа с файлами
5 years ago
Хирецкий Михаил dd56b3dab0 Рефакторинг: работа с файлами
5 years ago
Хирецкий Михаил e4fa7c25b2 Изменён выбора файловой системы по умолчанию
5 years ago
Хирецкий Михаил 637ef24386 btrfs-comp переименован в btrfs-compress
5 years ago
Хирецкий Михаил b5635a3a6a Исправлен синтаксис
5 years ago
Хирецкий Михаил 06d93fbccc Добавлена проверка на устновку значения для cl_autopartiton_default_format
5 years ago
Хирецкий Михаил ae4acc744f Исключён из сжатия btrfs /var/calculate/linux и linux пути
5 years ago
Хирецкий Михаил e0cddd5831 Добавлен путь отключения сжатия btrfs для grub, исправлено формирование fstab
5 years ago
Хирецкий Михаил 74f24e86be Исправлено монтирование btrfs-comp
5 years ago
Хирецкий Михаил e76ea7985f Исправлена возможность выбора файловой системы при авторазметке
5 years ago
Хирецкий Михаил 5c2d6cfee0 Добавлена возможность ставить систему на btrfs с сжатием
5 years ago
Хирецкий Михаил 15e747257a Изменено вычисление переменной os_install_clock_type
5 years ago
Хирецкий Михаил 73f15496f2 Исправлено вычисление корня при авторазметке
5 years ago
Хирецкий Михаил b109623110 Удалена ссылка на IRC чат в русской справке на livecd
6 years ago
Хирецкий Михаил 8065b1ecb2 Исправлено определение os_chrootable_set
6 years ago
Хирецкий Михаил 96be7db2ab Заблокирована попытка уставновки дистрибутива в который нельзя выполнить chroot
6 years ago
Хирецкий Михаил cdd5e1c3f4 Изменёно выполнение grub-install
6 years ago
Хирецкий Михаил d6851726f2 Изменена проверка достпности записи в /run
6 years ago
Хирецкий Михаил fa37b9bbe3 Добавлены комментарии
6 years ago
Хирецкий Михаил cebf7ebea2 Исправлен запуск cl-install в readonly системе
6 years ago
Хирецкий Михаил 7cae9b9073 При установке системы chroot_status задаётся принудительно
6 years ago
Хирецкий Михаил 1b87cd19e7 Добавлена поддержка initramfs с early microcode
6 years ago
Хирецкий Михаил 2e67de479d ALSA по умолчанию
6 years ago
Хирецкий Михаил 1f0b7ed156 Исправлено вычисление звуковых переменных при отсутствии звуковых карт
6 years ago
Хирецкий Михаил c621888a53 Добавлены переменные для настройки asound.conf через идентификаторы карт
6 years ago
Хирецкий Михаил f39b0b2756 Исправлена установка на xfs с отдельным /boot
6 years ago
Хирецкий Михаил 648665965d Исправлена установка системы на xfs раздел
6 years ago
Хирецкий Михаил 60d75fc48b Изменено сообщение об ошибке при выборке EFI, изменено определение использования EFI раздела
6 years ago
Хирецкий Михаил 94060a2e4f Обновлён handbook
6 years ago
Хирецкий Михаил bbb69e5e50 Изменена установка nvidia-drivers во вермя загрузки системы
6 years ago
Хирецкий Михаил d006b91da3 Исключены двойное описание маршрута на один и тот же адрес
6 years ago
Хирецкий Михаил 0bc330ee9e Добавлена возможность настройки типа аппаратных часов (локальное время или UTC)
6 years ago
Хирецкий Михаил dda9e6d7f7 Исправлен перенос текущих пользователей при установке системы
6 years ago
Хирецкий Михаил 1dda7569dc Исправлена проверка переключения OpenGL
6 years ago
Хирецкий Михаил 8a7c7896cd Добавлена возможность выбора раскладки отдельно от локали
6 years ago
Хирецкий Михаил b75cb75f72 Изменена логика авторазметки
6 years ago
Хирецкий Михаил 688c332ad4 Исправлена инициализация сети при первой загрузке
6 years ago
Хирецкий Михаил 25cb9f28b5 Испралена настройка сети при первой загрузке и livecd
6 years ago
Хирецкий Михаил e0fad90a71 Merge remote-tracking branch 'origin/master-3.5'
6 years ago
Хирецкий Михаил ce76550392 Исправлен выбор разрешения для фреймбуфера в UEFI
6 years ago
Хирецкий Михаил 71197caada Удалена переменная для выбора framebuffer разрешения из cl-setup-video
6 years ago
Хирецкий Михаил b9539958a7 Изменён алгоритм получения текущего разрешения для X
6 years ago
Хирецкий Михаил 75cd00ab4b Изменён алгоритм вычисление разрешения для фреймбуффера
6 years ago
Хирецкий Михаил fb50c709e9 Отказ от вычисления разрешения framebuffer
6 years ago
Хирецкий Михаил 8f187edb86 Исправлен скрипт загрузки системы для lxc (merge with origin/master-3.5)
6 years ago
Хирецкий Михаил 64cb021046 Добавлено восстановление file capabilities по файлу описанию
6 years ago
Хирецкий Михаил b7f58754c2 Добавлен запуск calculate в lxc, исправлена настройка сети
6 years ago
Хирецкий Михаил 5575c18520 Изменена инициализация системы для lxc и livecd
6 years ago
Хирецкий Михаил f0cfadc55f Синхронзиация переводов
6 years ago
Хирецкий Михаил e2883a46b9 Удалёно обнволение зависимостей запуска в init.d/calculate если это не live
6 years ago
Хирецкий Михаил b8c38a7aa2 Изменены параметры для настройки сети и авторазметки
6 years ago
Хирецкий Михаил 264c8a66e5 Исправлен параметр alsa и x11
6 years ago
Хирецкий Михаил 0dbc20ab5b Исправлен параметр --route
6 years ago
Хирецкий Михаил 41158e98a2 Удалён вызов смены IO планировщика при cl-setup-boot
6 years ago
Хирецкий Михаил 5f0d019ae2 Удалён параметр настройка IO планировщика
6 years ago
Хирецкий Михаил 114184b7f6 Включен composite для amdgpu по умолчанию
6 years ago
Хирецкий Михаил 8bc147a172 Обновление фраз
7 years ago
Хирецкий Михаил f041dcbed3 Обновлены фразы
7 years ago
Хирецкий Михаил 14c755b269 Изменена таблица точек монтирования, выводимая перед установкой
7 years ago
Хирецкий Михаил d6da45321d Исправлено определение дисков из которых состоит RAID при определении IO планировщика
7 years ago
Хирецкий Михаил ee1d077076 Добавлено определение QEMU виртуальных дисков
7 years ago
Хирецкий Михаил 6687f99bca Исправлно проверка устройства, на которое ставится система как на Flash
7 years ago
Хирецкий Михаил 626209b32e Исправлено определение flash устройства
7 years ago
Хирецкий Михаил 167ab9c10e Исправлено использование методов модуля distr
7 years ago
Хирецкий Михаил 6e85862f33 Remove outdated code
7 years ago
Хирецкий Михаил 7fb3663fd3 Исправлено определение необходимости обновление nvram записи
7 years ago
Хирецкий Михаил cf60ba8800 Изменено алгоритм определения EFI разделов для авторазметки
7 years ago
Хирецкий Михаил d5f0a80358 Добавлена обрабока ошибок при авторазметке
7 years ago
Хирецкий Михаил 90f4296883 Изменён вид списка устройств для авторазметки
7 years ago
Хирецкий Михаил 221f24d6ff Изменена проверка совместимости --uefi и --mbr
7 years ago
Хирецкий Михаил a62401e819 Исправлен список устройств для установки mbr
7 years ago
Хирецкий Михаил b09e4e3dfa Исправлен порядок загрузки efi при raid
7 years ago
Хирецкий Михаил eebef51733 Исправлено определение parent устройства для авторазметки на RAID.
7 years ago
Хирецкий Михаил e9674b84c9 Изменена установка системы с EFI загрузчиком
7 years ago
Хирецкий Михаил 2b1868217d Рефакторинг
7 years ago
Хирецкий Михаил 3838464b11 Исправлены переменные cl_autopartition_disk_size, cl_autopartition_disk_size_full
7 years ago
Хирецкий Михаил 71b6a05939 Добавлено ожидание устройств при авторазметке
7 years ago
Хирецкий Михаил e7cefcd6e2 Добавлена обработка ошибок при создании разделов в авторазметке
7 years ago
Хирецкий Михаил 2682389436 Рефакторинг. Удаление неиспользуемого кода.
7 years ago
Хирецкий Михаил 23a5389c01 Добавлены проверки использования дисков для разметки
7 years ago
Хирецкий Михаил 24712fc9f1 Переписан модуль авторазметки
7 years ago
Хирецкий Михаил 89630bbfaf Изменено содержимое os_disk_parent
7 years ago
Хирецкий Михаил 2716260626 Рефакторинг
7 years ago
Хирецкий Михаил b1e46276fd Использование calculate-lib:Lvm
7 years ago
Хирецкий Михаил fa3b455d1f Рефакторинг
7 years ago
Хирецкий Михаил d9e1f446a1 Рефакторинг
7 years ago
Хирецкий Михаил 918c262f92 Рефакторинг. Вынос логики чтения /sys через отдельный класс.
7 years ago
Хирецкий Михаил 9570bea5ef Обновление вызовов в связи с рефакторингом calculate-lib LVM
7 years ago
Хирецкий Михаил 51b1432365 Обновление вызовов в связи с рефакторингом calculate-lib getUdevDeviceInfo
7 years ago
Хирецкий Михаил bc6c1a7ad2 Изменены опции загрузки dracut
7 years ago
Хирецкий Михаил 0e7fd021fb Исправлена миграция пользователей. (установка без пользователей)
7 years ago
Хирецкий Михаил d4fcc11fa2 Исправлен выбор групп для пользователя
7 years ago
Хирецкий Михаил 6268b21371 Удалена проверка при установки btrfs и dos
7 years ago
Хирецкий Михаил a592279cd0 Добавлена сортировка групп пользователя
7 years ago
Хирецкий Михаил ca49100504 Исправлено фразы
7 years ago
Хирецкий Михаил 319f9a2aec Исправлен выбор типа администратора для пользователя
7 years ago
Хирецкий Михаил 796438c279 Исправлен вызов cl-core для удаления локальных сертификатов
7 years ago
Хирецкий Михаил 81c01ae826 Обновлены значения для переменной миграции пользователей
7 years ago
Хирецкий Михаил 0f97259c1e Переименование значений переменных
7 years ago
Хирецкий Михаил edf3cbefc3 Исправлена миграция пользователей
7 years ago
Хирецкий Михаил 5061936d63 Добавлена настройка админов в устанавливаемую систему (2)
7 years ago
Хирецкий Михаил 96cf2427da Добавление guest в администраторы на livecd
7 years ago
Хирецкий Михаил 3280fab3a6 Исправлен init.d/calculate для настройки livecd
7 years ago
Хирецкий Михаил a26ddfc631 Исправлены поля выбора роли пользователя
7 years ago
Хирецкий Михаил f65739b4d3 Добавлена настройка админов в устанавливаемую систему
7 years ago
Хирецкий Михаил ec53b8a92a Добавлена настройка calculate-core при первой загрузке в init.d/calculate
7 years ago
Хирецкий Михаил e9ccb9d503 Модифицирован init.d/calculate
7 years ago
Хирецкий Михаил 1aff0b033f Добавлена возможность указывать пользователей администраторов
7 years ago
Хирецкий Михаил f6ac3b645e Исправлено указание сетевых маршрутов через cl-setup-network --route
7 years ago
Хирецкий Михаил 8ce1811d0e Отключена возможность установки системы из контейнеров
7 years ago
Хирецкий Михаил 2831d89668 Добавлена поддержка дистрибутива контейнер типа
7 years ago
Хирецкий Михаил 9bd75ef654 Исключение запуска в контейнере init.d/calculate
7 years ago
Хирецкий Михаил ecd210d899 Исправлен скрипт автовхода пользователя в Xorg сервере сеанс
7 years ago
Хирецкий Михаил c1ec3af29b Исправлены сообщения об ошибке
7 years ago
Хирецкий Михаил b9f5aad68e Исправлено изменение параметра use grub password при переустановке
7 years ago
Хирецкий Михаил f4f2940738 Пароль на grub по умолчанию для livecd
7 years ago
Хирецкий Михаил 19ef16d129 Переименованы параметры
7 years ago
Хирецкий Михаил 1ca4d18ad6 Исправлено определение наличия пароля root
7 years ago
Хирецкий Михаил 4156f6dd4b Исправлен работа с паролем root из shadow (поддержка только sha256)
7 years ago
Хирецкий Михаил fda9d5c48e Поддержка пароля для grub
7 years ago
Хирецкий Михаил 8c285d2792 Добавлена переменная os_install_x11_resolution_preferred
7 years ago
Хирецкий Михаил 1eba78b7ac Удалено повторное внесение загрузочной записи в nv-ram, если её параметры не менялись
7 years ago
Хирецкий Михаил c23191fa01 Оптимизирован алгоритм опредления изменений темы grub и splash
7 years ago
Хирецкий Михаил 5d2da6a18b Добавлена команда cl-setup-themes и переменные для её работы
7 years ago
Хирецкий Михаил 6ad5e6ad3a Исправлена установка на flash
7 years ago
Хирецкий Михаил 1afc8d5732 Исправлена создание пользовательской директории
7 years ago
Хирецкий Михаил ebff48f9d3 Исправлены права на homedir при создании guest
7 years ago
Хирецкий Михаил 1d8e753d89 Отключено создание bios_grub раздела авторазметкой с UEFI установкой
7 years ago
Хирецкий Михаил 95720642a5 Исправлена авторазметка по умолчанию для livecd
7 years ago
Хирецкий Михаил 74cc73cb63 Исправлена проверка наличия настроенного утилитами DHCP сервера
7 years ago
Хирецкий Михаил 3ac3478644 Включена авторазметка по умолчанию для установки системы с livecd
7 years ago
Хирецкий Михаил b2ea124cb8 Изменён вывод списка звуковых карт,устройств
7 years ago
Хирецкий Михаил ead5a0351c Добавлена обработка параметра /proc/cmdline calculate=audio:alsa
7 years ago
Хирецкий Михаил cc89cfb5b0 English update
8 years ago
Хирецкий Михаил 204edf162f Исправлена смена видеодрайвера
8 years ago
Хирецкий Михаил b156c6dade --audio-card -> --card
8 years ago
Хирецкий Михаил 8b13f20d67 Исправлена звуковая переменная (отображалась только последняя карта)
8 years ago
Хирецкий Михаил 158fe56af6 Изменён формат переменных os_audio_
8 years ago
Хирецкий Михаил a2879751ce Скрыты для отображаения параметры авторазметки root size, swap size
8 years ago
Хирецкий Михаил a2d822cf7f Добавлена переменная содержащая версию ядра в /usr/src/linux и
8 years ago
Хирецкий Михаил 52cd2e9c68 Запрет на " " в имени хоста
8 years ago
Хирецкий Михаил ae74fbcd31 Добавлена переменная cl_install_kernel_build для сборки нескольких ядер
8 years ago
Хирецкий Михаил 8cd503b289 Merge remote-tracking branch 'origin/master3.4'
8 years ago
Хирецкий Михаил a74dc0e99f Добавлена поддержка bond интерфейсов
8 years ago
Хирецкий Михаил 4428ae5cc1 Исправлено определения установки загрузчика при авторазметке
8 years ago
Хирецкий Михаил 2072dd4b31 Обновлены иконки
8 years ago
Хирецкий Михаил 287e88695f Merge remote-tracking branch 'origin/master3.4'
8 years ago
Хирецкий Михаил 3719da0cef Обновлён handbook
8 years ago
Хирецкий Михаил 9dd4fd602e Подготовка к alpha
8 years ago
Хирецкий Михаил 5b7dbcf107 Исправлен сценарий init.d
8 years ago
Хирецкий Михаил d05e12b708 Исправлена опечатка
8 years ago
Хирецкий Михаил b1e3a165cc Добавлена поддержка установки на mmcblk
8 years ago
Хирецкий Михаил d6274f96b8 Обновлён handbook (добавлен CLDC)
8 years ago
Хирецкий Михаил e51e26db0e Исправлена переменная для настройки звука
8 years ago
Хирецкий Михаил 6630986bdf Добавлена настройка звука
8 years ago
Хирецкий Михаил 99055edd9c Добавлена поддержка kbd
8 years ago
Хирецкий Михаил fd7bfef8d4 Добавлена поддержка установки на NVME диски
8 years ago
Хирецкий Михаил 728c16d76b Fix comment
8 years ago
Хирецкий Михаил 3a49f2f216 Изменён список предлагаемых --os при установке. Обновлён handbook.
8 years ago
Хирецкий Михаил 09593fc440 Сообщения
8 years ago
Хирецкий Михаил a5ad88cb83 Доработана опция --autologin
8 years ago
Хирецкий Михаил 30956c2061 Исправлена настройка cl_install_dev_from при авторазметке
8 years ago
Хирецкий Михаил 6cfc2cc4e7 Изменён механизм фильтра исключения для squash
8 years ago
Хирецкий Михаил eedc6ca5be Добавлена подерржка include в создание squash образа
8 years ago
Хирецкий Михаил bb6d75aadb Обновлён handbook (удалён CLSK)
8 years ago
Хирецкий Михаил d82e045462 Добавлена проверка при удалении пустой директорий: возможно она примонтированная
8 years ago
Хирецкий Михаил b13b7a3fb0 Update copyrights.
8 years ago
Хирецкий Михаил 58c37b4c55 Удалена поддержка nilfs2
8 years ago
Хирецкий Михаил 56b5544442 Изменён --help для параметра cl-install --disk
8 years ago
Хирецкий Михаил b117dee319 Добавлена поддержка amdgpu
8 years ago
Хирецкий Михаил c78580366b Исправлена переменная для добавления пользователей
8 years ago
Хирецкий Михаил 2220a89206 Обновлён список выбираемых видеодрайверов
8 years ago
Хирецкий Михаил 8cf1c4e851 Исправление для переменной в модуле builder
8 years ago
Хирецкий Михаил e1ecee0a6f Обновлены handbook
8 years ago
Хирецкий Михаил 470de38099 Удаление init.d/calculate из автозапуска перенесено в start()
8 years ago
Хирецкий Михаил f49fba4268 Изменено получения параметров из /proc/cmdline
9 years ago
Хирецкий Михаил dbaf526a0f Оптимизированная установка проприетарного видеодрайвера во время загрузки системы
9 years ago
Хирецкий Михаил 0cebbb21ae Исправлена миграция пользоватлей
9 years ago
Хирецкий Михаил 28b50c6ab5 Исправлена установка проприетарного видеодрайвера во время загрузки
9 years ago
Хирецкий Михаил 96a518a14a Новые параметры авторазметки
9 years ago
Хирецкий Михаил f87e69036a Изменены параметры авторазметки
9 years ago
Хирецкий Михаил 6a30944acc Удалена перенастройка env в init.d/calculate (вынесена в утилиты)
9 years ago
Хирецкий Михаил e307f7e4ae Исправлена ошибка иморта из ldap
9 years ago
Хирецкий Михаил 22ee2dd6e7 Изменён порядок языков
9 years ago
Хирецкий Михаил 9fef72b8ac Переработана локализация
9 years ago
Хирецкий Михаил 04c2a0cc55 Подбавлено перемонтирование Flash
9 years ago
Хирецкий Михаил 6aa6ad992e Перемонтирование live flash при загрузке в rw
9 years ago
Хирецкий Михаил d38f9efcb3 Отключено предложение перезагрузки при установки на flash
9 years ago
Хирецкий Михаил b11ef4b868 Изменена сортировка языков (по локали, а не по названию)
9 years ago
Хирецкий Михаил 4f53217c15 Исправлна установка на flash подключенную пользователем
9 years ago
Хирецкий Михаил 7e6394161e Исправления для установки на USB Flash
9 years ago
Хирецкий Михаил adbd4cf890 Установка на Flash отдельной командой
9 years ago
Хирецкий Михаил b1cec40387 Изменён порядок опций для установки на flash
9 years ago
Хирецкий Михаил 7822263952 Добавлена переустановка системы без форматирования
9 years ago
Хирецкий Михаил f2d835b8f1 Добавлена перенастройка локалей при первой загрузки с hdd
9 years ago
Хирецкий Михаил f7544d5f19 Исправление для ускоренной запаковки
9 years ago
Хирецкий Михаил 9f6eba1899 Исправления для live grub
9 years ago
Mike Khiretskiy 4fa0ca3334 Revert "Исправлено одновременное разворачивание нескольких образов"
9 years ago
Хирецкий Михаил 23dad7df15 Исправлено одновременное разворачивание нескольких образов
9 years ago
Mike Khiretskiy c49111c8d4 Обновлён handbook
9 years ago
Mike Khiretskiy 34feb36510 Добавлена переменная текущего конфига ядра
9 years ago
Mike Khiretskiy 20fb25e10f Исправлено восстанволение данных о монтировании из json
9 years ago
Mike Khiretskiy 5bdef0490b Refactoring
9 years ago
Mike Khiretskiy 6f82626d8c Исправлена запаковка образа
9 years ago
Mike Khiretskiy f6307ea7e8 Revert "Удалён handbook"
9 years ago
Mike Khiretskiy a6a01f91bc Изменены иконки
9 years ago
Mike Khiretskiy d846a733c6 Исправлен init.d/calculate
9 years ago
Mike Khiretskiy 1d50ecdecb Удалён handbook
9 years ago
Mike Khiretskiy 411853f84e Исправлен init.d/calculate (удаление проприетарных драйверов)
9 years ago
Mike Khiretskiy 65523dd804 Исправлено создание iso образов для 64бит
9 years ago
Mike Khiretskiy e588b2593e Изменено нумерование директорий iso, iso.01, iso.02
9 years ago
Mike Khiretskiy f99fc00ae9 Добавлено сравнение serial_id у образов при выборе лучшего
9 years ago
Mike Khiretskiy 60131ba483 Добавлена возможность автопоиска образа из cld-20150909-2-x86_64.iso имён
9 years ago
Mike Khiretskiy 62b25589f5 Добавлена переменная базовой системы, переименована переменная os_install_dev_from
9 years ago
Mike Khiretskiy 88935d471d Обновлены иконки
9 years ago
Mike Khiretskiy ad2f878ba9 Обновление иконок
9 years ago
Mike Khiretskiy 85b133ce0b Исправлена установка системы на flash с CD
9 years ago
Mike Khiretskiy d2bab2ff8f Исправлен скрипт установки видео драйвера
9 years ago
Mike Khiretskiy f8983e4409 Добавлено удаление packages
9 years ago
Mike Khiretskiy 45d1268a2b Исправлена установка проприетарного драйвера во время загрузки
9 years ago
Mike Khiretskiy 592985b59b Голландский язык
9 years ago
Mike Khiretskiy f48612966f Исправлено прерывание сборки после перезагрузки
9 years ago
Mike Khiretskiy 1c04f4c88c Изменена схема авторазметки по умолчанию
9 years ago
Mike Khiretskiy 3726c624b8 Монтирование устройств при установке в /run/calculate/mount
9 years ago
Mike Khiretskiy 8348e0678e Исправлено копирование файла при установке на флешку
9 years ago
Mike Khiretskiy 7bce904451 Исправлена запаковка в squash
9 years ago
Mike Khiretskiy 39339e72bb Добавлен отладочный блок для быстрого создания iso образов
9 years ago
Mike Khiretskiy c4ce2cfdfd Множественые изменения для использования в calculate-assemble
9 years ago
Mike Khiretskiy 6b5bd12637 Fallback разрешение для x11_resolution
9 years ago
Mike Khiretskiy 3764fe66c6 Композит для xorg включен для драйвера по умолчанию
9 years ago
Mike Khiretskiy 6ea7b23d33 Изменены параметры авторазметки
9 years ago
Mike Khiretskiy 7d469d6a59 Изменен регистр MAC адреса у переменной сетевых карт
9 years ago
Mike Khiretskiy c63db96de0 Исправлено получения списка дистрибутивов на livecd
9 years ago
Mike Khiretskiy bc12d73d79 Оптимизация init.d/calculate
9 years ago
Mike Khiretskiy 43a5eaea37 Использование portage вместо emerge --info
9 years ago
Mike Khiretskiy 81a389428d Исправлено разрешение по умолчанию
9 years ago
Mike Khiretskiy 1fdccafb2a Переход на скрипт cl-variable
9 years ago
Mike Khiretskiy 12309eb024 Добавлено определение виртуальных дисков на VMWare и kvm (virtio)
9 years ago
Mike Khiretskiy 40a50bd200 Изменена короткая опция для --autopartition (-p)
9 years ago
Mike Khiretskiy a77228ae30 Добавлены короткие опции к --autopartition, --auto-scheme, --partition-table
9 years ago
Mike Khiretskiy ae3142cfc9 Исправлено вычисление конфига ядра в образе
9 years ago
Mike Khiretskiy 524ae39d9f os_net_interfaces_orig отмечена как depricated
9 years ago
Mike Khiretskiy 1e0411bc4c Переписано определение параметров ядра.
9 years ago
Mike Khiretskiy 6d858595b2 Добавлено определение виртуальных дисков от VirtualBox
9 years ago
Mike Khiretskiy 93065c7131 Поддержка eudev
9 years ago
Mike Khiretskiy 5a9044954b Исправлена зависимость от calculate-lib
9 years ago
Mike Khiretskiy ee5e2d0971 Добавлены опция discard при монтировании ssd для файловых систем xfs, jfs, fat
9 years ago
Mike Khiretskiy bf188be7c7 Добавлена опция discard для монтирования ext4
9 years ago
Mike Khiretskiy 0af4cb0759 Изменена установка планировщика
9 years ago
Mike Khiretskiy 5d49c0a941 Вывод сообщения о перезагрузке только при cl-setup-video
9 years ago
Mike Khiretskiy 30149612f0 Исправлено отображение данных перед установкой на flash
9 years ago
Mike Khiretskiy f3b339fb58 Исправлено определение сетевых имен
10 years ago
Mike Khiretskiy 1cece55f61 Исправлен скрипт автовхода в X сессию
10 years ago
Mike Khiretskiy 105d06313c Исправлена ошибка параметров по умолчанию для swap
10 years ago
Mike Khiretskiy eff5a952db Добавлены дополнительные опции монтирования для ssd btrfs
10 years ago
Mike Khiretskiy 8181f67ec9 Обновлено руководство пользователя
10 years ago
Mike Khiretskiy 102c44bdec Добавлена поддержка grub2.02
10 years ago
Mike Khiretskiy 3c2dfe4cdd Исправлено удаление init.d/calculate из автозапуска
10 years ago
Mike Khiretskiy fb54292eed Исправлино определение CD устройства
10 years ago
Mike Khiretskiy 26ca8667d1 Изменения для авторазметки
10 years ago
Mike Khiretskiy 30e55b91a2 Исправлена установка на kvm virtio диски
10 years ago

6
.gitignore vendored

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

@ -1,5 +1,5 @@
#!/bin/bash
# Copyright 2011 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2011-2016 Mir Calculate. 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 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2011-2016 Mir Calculate. 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,6 +21,8 @@ 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
@ -43,6 +45,30 @@ 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
@ -68,45 +94,54 @@ do
# perform user profile setting up
X ${DISPLAYNUM} -auth $XAUTHORITY vt${TTYNUM} -noreset &
XPID=$!
env USER=${XUSER} /usr/share/calculate/xdm/xdm --login || break
# write pam enviroment for pam_ck_connector
cat >/home/${XUSER}/.pam_environment <<EOF
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
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"
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 ]]
# 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
sleep $WAITRELOGIN
/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
fi
env USER=${XUSER} /usr/share/calculate/xdm/xdm --logout
[[ -n $XPID ]] && kill $XPID
wait $XPID
done

@ -1,5 +1,5 @@
#!/sbin/runscript
# Copyright 2011 Calculate Ltd. http://www.calculate-linux.org
#!/sbin/openrc-run
# Copyright 2011-2016 Mir Calculate. 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,17 +13,24 @@
# 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 xdm
before keymaps consolefont dbus display-manager local
use swap hostname
keyword -timeout
keyword -timeout -docker -systemd-nspawn -vserver
}
check_install_ability()
{
local pkg=$1
FEATURES="-getbinpkg" FETCHCOMMAND=false DISTDIR=/usr/portage/distfiles emerge -fq $pkg &>/dev/null
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
}
is_already_install()
@ -39,21 +46,33 @@ install_pkg()
{
local pkg=$1
ebegin "Installing $pkg"
FEATURES="-getbinpkg" FETCHCOMMAND=false DISTDIR=/usr/portage/distfiles emerge $pkg &>/dev/null
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
}
new_install_pkg()
{
local pkg=$1
local mask=$2
pkg=`echo $pkg | cut -d\/ -f2`
ebegin "Installing $pkg"
FETCHCOMMAND=false DISTDIR=/usr/portage/distfiles /usr/local/sbin/cl-video-install $pkg &>/dev/null
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
eend $?
}
variable_value()
{
local varname=$1
/usr/sbin/cl-core-variables-show --only-value $varname
/usr/libexec/calculate/cl-variable --value $varname
}
install_video_driver()
@ -65,8 +84,11 @@ install_video_driver()
;;
nvidia)
local nvidiamask=`variable_value install.os_nvidia_mask`
[[ -n $nvidiamask ]] && \
if [[ -n $nvidiamask ]]
then
[[ -d /etc/portage/package.mask ]] || mkdir /etc/portage/package.mask
echo $nvidiamask >/etc/portage/package.mask/nvidia
fi
local drv="x11-drivers/nvidia-drivers"
;;
*)
@ -77,9 +99,9 @@ install_video_driver()
then
if ! is_already_install $drv
then
if [[ -x /usr/local/sbin/cl-video-install ]]
if [[ -x ${CL_VIDEO_INSTALL} ]]
then
new_install_pkg $drv
new_install_pkg $drv $nvidiamask
else
check_install_ability $drv && install_pkg $drv
fi
@ -102,8 +124,9 @@ 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,scanner,uucp \
--groups users,wheel,audio,cdrom,video,cdrw,usb,plugdev,games,lp,lpadmin,scanner,uucp \
${nonroot_user}
chmod 700 /home/${nonroot_user}
eend $?
fi
}
@ -126,41 +149,101 @@ 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
}
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" ]]
restore_filecaps() {
if [[ -f /var/lib/calculate/filecaps ]] && type filecap &>/dev/null
then
touch /* /bin/* /sbin/*
udevadm trigger --action="add" --subsystem-match=net
while read line;
do
filecap $line
done </var/lib/calculate/filecaps
fi
/sbin/rc-update --update
return 0
rm -f /var/lib/calculate/filecaps
}
stop() {
local roottype=`variable_value main.os_root_type`
if [[ $roottype == "hdd" ]] && rc-config list boot | grep -q "calculate "
start() {
if rc-config list boot | grep -q -e "calculate " -e "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
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
# 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!"
fi
return 0
}

@ -0,0 +1,50 @@
#!/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="Installation-Guide">Installation Guide<a href="#Installation-Guide" class="wiki-anchor">&para;</a></h1>
<h1 id="Quick-Installation-Guide">Quick Installation Guide<a href="#Quick-Installation-Guide" class="wiki-anchor">&para;</a></h1>
<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>
<h2 id="Welcome-to-Calculate-Linux-">Welcome to Calculate Linux !<a href="#Welcome-to-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, 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>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>Below is the complete list of our distributions with their abbreviations:</p>
@ -31,134 +31,116 @@ pre {font-size:133% }
<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>
<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>
</ul>
<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>
<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>
<h2 id="Network-configuration">Network configuration<a href="#Network-configuration" class="wiki-anchor">&para;</a></h2>
<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>
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>
<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 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>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>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>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>To view the list of all existing partitions, open the console as <em>root</em> and type:<br /><pre>
<p>To list all existing partitions, open your terminal as <em>root</em> and type:<br /><pre>
fdisk -l
</pre></p>
<p>Note: To obtain <em>root</em> rights in console mode, use <code>su</code> or <code>sudo</code>.</p>
<p>Note: To obtain the <em>root</em> priveleges 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>
<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:
We provide several tools that get you install Calculate Linux. You can choose between :
<ul>
<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>
<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>
</ul>
<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>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>
<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>
<p><em>Before you begin, we highly recommend that you make a backup of your data on a flash drive.</em></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>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>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="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>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>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>
<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
</pre></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>
<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>
<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>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>
<h2 id="System-update">System update<a href="#System-update" class="wiki-anchor">&para;</a></h2>
<h2 id="Update">Update<a href="#Update" class="wiki-anchor">&para;</a></h2>
<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>
<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
<p>To sync the list of packages and update all of your software, simply run:<br /><pre>
cl-update
</pre></p>
<p>For further updates of all your software, run:<br /><pre>
emerge -uDNa world
<p>Or, if you want to update the list only, for the time being:<br /><pre>
cl-update --sync-only
</pre></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>
<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>
<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, 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>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>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>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>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><em>Enjoy!</em><br /><em>Calculate Linux Team.</em></p>
<p>&nbsp;<br /><em>Enjoy!</em><br /><em>Calculate Linux Team.</em></p>
</body>
</html>

@ -1,163 +0,0 @@
<!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>

@ -1,165 +0,0 @@
<!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.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!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</title>
@ -15,29 +15,32 @@ 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 Portages. Дистрибутив распространяется в виде установочного образа, содержащего лучшее программное обеспечение. Большая часть программ имеет свободную лицензию, позволяющую не только устанавливать и распространять, но и модифицировать исходный код.</p>
<p>Мы постарались сделать для вас максимально удобную для работы систему, используя оригинальный установщик, переработанный интерфейс, шаблоны настройки, утилиты Calculate и Gentoo Portage. Дистрибутив распространяется в виде установочного образа, содержащего лучшее программное обеспечение. Большая часть программ имеет свободную лицензию, позволяющую не только устанавливать и распространять, но и модифицировать исходный код.</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>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>
</ul>
<p>Для получения прав администратора системы, запущенной с LiveCD, используйте логин <em>root</em> с паролем <strong>root</strong>. Доступ к рабочему столу CLD, CLDG и CLDX выполняется пользователем <em>guest</em> с паролем <strong>guest</strong>.</p>
<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>
<h2 id="Настройка-сети">Настройка сети<a href="#Настройка-сети" class="wiki-anchor">&para;</a></h2>
@ -51,16 +54,16 @@ pre {font-size:133% }
</ul>
<p>Подробнее в разделе <a href="http://www.calculate-linux.ru/main/ru/setup_network" class="wiki-page">Настройка сети</a>.</p>
<p>Подробнее в разделе <a href="https://www.calculate-linux.ru/main/ru/setup_network" target="_blank">Настройка сети</a>.</p>
<h2 id="Разбивка-диска">Разбивка диска<a href="#Разбивка-диска" class="wiki-anchor">&para;</a></h2>
<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 мы рекомендуем использовать раздел не менее 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 для изменения разделов диска используется программа <em>Gparted</em>. В CDS, CSS и CLS входят только консольные утилиты: <em>fdisk</em>,<em>gdisk</em> или <em>cfdisk</em>.</p>
<p>В CLD, CLDC, CLDL, CLDM и CLDX для изменения разделов диска используется программа <em>Gparted</em>. В CDS, CSS и CLS входят только консольные утилиты: <em>fdisk</em>,<em>gdisk</em> или <em>cfdisk</em>.</p>
<p>Чтобы просмотреть список существующих разделов, откройте консоль с правами пользователя <em>root</em> и наберите:<br /><pre>
@ -82,13 +85,13 @@ fdisk -l
Установить систему Calculate Linux вы можете одним из перечисленных способов:
<ul>
<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>
<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>
</ul>
<p>Система может быть установлена из squashfs-образа, если Вы загрузились с liveCD или USB Flash, либо из ISO-файла, размещенного в директории <code>/var/calculate/linux</code> или <code>/var/calculate/remote/linux</code>. Во втором случае Вы можете установить любую версию дистрибутива поддерживаемой архитектуры.</p>
<p>Система может быть установлена из squashfs-образа, если Вы загрузились с liveCD или USB Flash, либо из ISO-файла, размещенного в директории <code>/var/calculate/linux</code>.</p>
<p>Сервер утилит, консольный и графический клиенты входят в состав Calculate Linux, но могут быть установлены из оверлея Calculate в любом Gentoo-совместимом дистрибутиве.</p>
@ -96,16 +99,15 @@ fdisk -l
Подробное описание установки смотрите в соответствующих разделах:
<ul>
<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>
<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>
</ul></p>
<h2 id="Первый-запуск">Первый запуск<a href="#Первый-запуск" class="wiki-anchor">&para;</a></h2>
<p>Если вы не указали других пользователей, после установки CLD, CLDG и CLDX в системе будут заведены две учётные записи, <em>root</em> и <em>guest</em>. Доступ к графическому сеансу может получить любой пользователь, кроме <em>root</em>. По умолчанию у пользователя <em>guest</em> установлен пароль <strong>guest</strong>.</p>
<p>Если вы не указали других пользователей, после установки CLD, CLDC, CLDL, CLDM и CLDX в системе будут заведены две учётные записи, <em>root</em> и <em>guest</em>. Доступ к графическому сеансу может получить любой пользователь, кроме <em>root</em>. По умолчанию у пользователя <em>guest</em> установлен пароль <strong>guest</strong>.</p>
<p>После установки в CLS нет графического приглашения к вводу пароля. Для запуска оконного менеджера выполните:<br /><pre>
@ -113,7 +115,7 @@ startx
</pre></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>Для получения прав пользователя <em>root</em> используйте команду <code>su</code>. Добавление новых пользователей подробно описано <a href="https://www.calculate-linux.ru/main/ru/create_system_users" target="_blank">здесь</a>.</p>
<p>По умолчанию вы можете зайти в систему удаленно (по протоколу ssh) только как пользователь root. В файле <code>/etc/ssh/sshd_config</code> в значение параметра <em>AllowUsers</em> можно добавить другие учётные записи. Мы рекомендуем убрать права удаленного доступа к системе для пользователя <em>root</em>.</p>
@ -122,27 +124,31 @@ startx
<h2 id="Обновление">Обновление<a href="#Обновление" class="wiki-anchor">&para;</a></h2>
<p>Calculate Linux использует rolling-release модель обновлений. Вы можете обновлять систему практически неограниченное количество раз, используя менеджер установки программ <a href="http://www.calculate-linux.ru/main/ru/emerge" class="external">emerge</a>. Перед установкой и обновлением программ, обновите портежи:<br /><pre>
eix-sync
<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
</pre></p>
<p>Для обновления программ, выполните:<br /><pre>
emerge -uDNa world
<p>Если вы хотите только обновить список пакетов, то выполните:<br /><pre>
cl-update --sync-only
</pre></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>
<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>
<h2 id="Помощь">Помощь<a href="#Помощь" class="wiki-anchor">&para;</a></h2>
<p>Если установка системы вызвала сложности или вы хотите поделиться своим впечатлением, зайдите на <em>IRC</em> канал <em>#calculate-ru</em> (сервер FreeNode) сообщества пользователей Calculate Linux. Для этого достаточно воспользоваться иконкой <em>Xchat</em> на вашем рабочем столе.</p>
<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>Сайт проекта: <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>Сайт проекта: <a href="https://www.calculate-linux.ru" target="_blank">https://www.calculate-linux.ru</a></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-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2010-2016 Mir Calculate. 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,12 +17,13 @@
__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-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2010-2016 Mir Calculate. 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,141 +14,197 @@
# 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__])
class FileSystemManager:
setLocalTranslate('cl_install3', sys.modules[__name__])
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 = {
'ext2': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext2',
'formatparam': '{labelparam} {device}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '83',
'type':['hdd','usb-hdd']},
'ext3': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext3',
'formatparam': '{labelparam} {device}',
'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}',
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '83',
'type':['hdd','usb-hdd']},
'ext4': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext4',
'formatparam': '{labelparam} {device}',
'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}',
'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}',
'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',
'type':['hdd','usb-hdd']},
'xfs': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.xfs',
'formatparam': '{labelparam} -f {device}',
'compress': None,
'type': ['hdd', 'usb-hdd']},
'ext3': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext3',
'formatparam': '{labelparam} {device}',
'gpt': '8300',
'label': '-L {labelname}',
'ssd': [],
'msdos': '83',
'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}',
'compress': None,
'type': ['hdd', 'usb-hdd']},
'ext2': {'defaultopt': defaultOpt,
'format': '/sbin/mkfs.ext2',
'formatparam': '{labelparam} {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,
'gpt': '8300',
'label': '-L {labelname}',
'msdos': '7',
'compatible':['ntfs']}}
'msdos': '83',
'compress': None,
'ssd': []}
@classmethod
def firstAvailable(cls,listFS):
def firstAvailable(cls, listFS):
for fs in listFS:
if path.exists(cls.supportFS['format']):
return fs
else:
return ""
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 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'
@classmethod
def getDefaultOpt(cls,fs):
return ",".join(cls.supportFS.get(fs,{'defaultopt':[]})['defaultopt'])
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 []))
@classmethod
def checkFSForTypeMount(cls,fs,roottype,mp):
if mp == '/boot/efi':
if not fs in ('uefi','vfat'):
def checkFSForTypeMount(cls, fs, roottype, mp):
if mp.startswith('/boot/efi'):
if fs not 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-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2010-2016 Mir Calculate. 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,22 +17,30 @@
import os, sys, re, time
from calculate.lib.encrypt import encrypt
from os import path
from calculate.lib.utils.files import pathJoin
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.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"""
return filter(lambda x: len(x)==lenData,
map(lambda x: x.rstrip().split(":"), open(fileName)))
with open(fileName) as f:
return [x[:lenData] for x
in (y.rstrip().split(":") for y
in f)
if len(x) >= lenData]
class migrateGroups(_shareData):
"""Migrate group to new system"""
@ -51,46 +59,43 @@ class migrateGroups(_shareData):
def getThisData(self):
"""Get data migrate groups in this system"""
return filter(lambda x:\
self._reNumb.match(x[2]) and self.minGid<=int(x[2])<=self.maxGid,
self.getData())
return [x for x in self.getData()
if self._reNumb.match(x[2]) and self.minGid <= int(x[2]) <= self.maxGid]
def getNewData(self):
"""Get data migrate groups in new system"""
fileName = pathJoin(self.prefixNewSystem, self.fileGroups)
return filter(lambda x:\
self._reNumb.match(x[2]) and self.minGid<=int(x[2])<=self.maxGid,
self.getData(fileName=fileName))
return [x for x in self.getData(fileName=fileName)
if self._reNumb.match(x[2]) and self.minGid <= int(x[2]) <= self.maxGid]
def getNewDataSystemGroups(self):
"""Get data system groups in new system"""
fileName = pathJoin(self.prefixNewSystem, self.fileGroups)
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))
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)]
def getNewProcessedData(self):
"""Get processed data migrate groups in new system"""
# data this Group no users
dataThisGroupsNoUsers = map(lambda x: x[:3]+[""], self.getThisData())
dataThisGroupsNoUsers = [x[:3] + [""] for x in self.getThisData()]
dataNewGroups = self.getNewData()
namesNewGroups = map(lambda x: x[0], dataNewGroups)
gidsNewGroups = map(lambda x: x[2], dataNewGroups)
namesNewGroups = [x[0] for x in dataNewGroups]
gidsNewGroups = [x[2] for x in dataNewGroups]
for data in dataThisGroupsNoUsers:
nameGroup = data[0]
gid = data[2]
if nameGroup in namesNewGroups:
dataNewGroups = filter(lambda x: x[0]!=nameGroup,dataNewGroups)
namesNewGroups = map(lambda x: x[0], dataNewGroups)
gidsNewGroups = map(lambda x: x[2], dataNewGroups)
dataNewGroups = [x for x in dataNewGroups if x[0] != nameGroup]
namesNewGroups = [x[0] for x in dataNewGroups]
gidsNewGroups = [x[2] for x in dataNewGroups]
if gid in gidsNewGroups:
dataNewGroups = filter(lambda x: x[2]!=gid, dataNewGroups)
namesNewGroups = map(lambda x: x[0], dataNewGroups)
gidsNewGroups = map(lambda x: x[2], dataNewGroups)
dataNewGroups = [x for x in dataNewGroups if x[2] != gid]
namesNewGroups = [x[0] for x in dataNewGroups]
gidsNewGroups = [x[2] for x in dataNewGroups]
systemGroupsNewData = self.getNewDataSystemGroups()
return systemGroupsNewData, dataNewGroups, dataThisGroupsNoUsers
class migrateUsers(_shareData):
"""Migrate users to new system"""
@ -108,82 +113,71 @@ class migrateUsers(_shareData):
def getThisData(self):
"""Get data migrate users in this system"""
return filter(lambda x:\
self._reNumb.match(x[2]) and self.minId<=int(x[2])<=self.maxId,
self.getData())
return [x for x in self.getData()
if self._reNumb.match(x[2]) and self.minId <= int(x[2]) <= self.maxId]
def getNewData(self):
"""Get data migrate users in new system"""
fileName = pathJoin(self.prefixNewSystem, self.filePasswd)
return filter(lambda x:\
self._reNumb.match(x[2]) and self.minId<=int(x[2])<=self.maxId,
self.getData(fileName=fileName))
return [x for x in self.getData(fileName=fileName)
if self._reNumb.match(x[2]) and self.minId <= int(x[2]) <= self.maxId]
def getNewDataSystemUsers(self):
"""Get data system users in new system"""
fileName = pathJoin(self.prefixNewSystem, self.filePasswd)
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))
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)]
def getThisDataSystemUsers(self):
"""Get data system users in this system"""
fileName = self.filePasswd
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))
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)]
def getNewProcessedData(self, migrateUsers=[]):
def getNewProcessedData(self, migrateUsers=()):
"""Get processed data migrate users in new system"""
dataThisUsers = self.getThisData()
if migrateUsers:
dataThisUsers = filter(lambda x: x[0] in migrateUsers,
dataThisUsers)
dataThisUsers = [x for x in dataThisUsers if x[0] in migrateUsers]
dataNewUsers = self.getNewData()
namesNewUsers = map(lambda x: x[0], dataNewUsers)
uidsNewUsers = map(lambda x: x[2], dataNewUsers)
namesNewUsers = [x[0] for x in dataNewUsers]
uidsNewUsers = [x[2] for x in dataNewUsers]
for data in dataThisUsers:
nameUser = data[0]
uid = data[2]
if nameUser in namesNewUsers:
dataNewUsers = filter(lambda x: x[0]!=nameUser, dataNewUsers)
namesNewUsers = map(lambda x: x[0], dataNewUsers)
uidsNewUsers = map(lambda x: x[2], dataNewUsers)
dataNewUsers = [x for x in dataNewUsers if x[0] != nameUser]
namesNewUsers = [x[0] for x in dataNewUsers]
uidsNewUsers = [x[2] for x in dataNewUsers]
if uid in uidsNewUsers:
dataNewUsers = filter(lambda x: x[2]!=uid, dataNewUsers)
namesNewUsers = map(lambda x: x[0], dataNewUsers)
uidsNewUsers = map(lambda x: x[2], dataNewUsers)
dataNewUsers = [x for x in dataNewUsers if x[2] != uid]
namesNewUsers = [x[0] for x in dataNewUsers]
uidsNewUsers = [x[2] for x in dataNewUsers]
systemUsersNewData = self.getNewDataSystemUsers()
systemUsersNewNames = map(lambda x: x[0], systemUsersNewData)
systemUsersNewUids = map(lambda x: x[2], systemUsersNewData)
systemUsersNewNames = [x[0] for x in systemUsersNewData]
systemUsersNewUids = [x[2] for x in systemUsersNewData]
systemUsersThisData = []
if migrateUsers:
# this users < minId
systemUsersThisData = filter(lambda x: int(x[2])<self.minId and\
x[0] in migrateUsers,
self.getThisDataSystemUsers())
systemUsersThisData = [x for x in self.getThisDataSystemUsers()
if int(x[2]) < self.minId and x[0] in migrateUsers]
for data in systemUsersThisData:
nameUser = data[0]
uid = data[2]
if nameUser in systemUsersNewNames:
systemUsersNewData = filter(lambda x: x[0]!=nameUser,
systemUsersNewData)
systemUsersNewNames = map(lambda x: x[0],
systemUsersNewData)
systemUsersNewUids = map(lambda x: x[2],
systemUsersNewData)
systemUsersNewData = [x for x in systemUsersNewData
if x[0] != nameUser]
systemUsersNewNames = [x[0] for x in systemUsersNewData]
systemUsersNewUids = [x[2] for x in systemUsersNewData]
if uid in systemUsersNewUids:
systemUsersNewData = filter(lambda x: x[2]!=uid,
systemUsersNewData)
systemUsersNewNames = map(lambda x: x[0],
systemUsersNewData)
systemUsersNewUids = map(lambda x: x[2],
systemUsersNewData)
systemUsersNewData = [x for x in systemUsersNewData
if x[2] != uid]
systemUsersNewNames = [x[0] for x in systemUsersNewData]
systemUsersNewUids = [x[2] for x in systemUsersNewData]
return (systemUsersThisData, systemUsersNewData,
dataNewUsers, dataThisUsers)
class migrateShadow(_shareData):
"""Migrate users to new system"""
@ -205,49 +199,52 @@ class migrateShadow(_shareData):
def getThisData(self):
"""Get data migrate users in this system"""
return filter(lambda x: x[0] in self.thisMigrateUsers, self.getData())
return [x for x in self.getData()
if x[0] in self.thisMigrateUsers]
def getNewData(self):
"""Get data migrate users in new system"""
return filter(lambda x: x[0] in self.newMigrateUsers,
self.getData(fileName=self.newFileName))
return [x for x in self.getData(fileName=self.newFileName)
if x[0] in self.newMigrateUsers]
def getNewDataSystemShadow(self):
"""Get data system users in new system"""
return filter(lambda x: x[0] in self.sysNewMigrateUsers,
self.getData(fileName=self.newFileName))
return [x for x in self.getData(fileName=self.newFileName)
if x[0] in self.sysNewMigrateUsers]
def getThisDataSystemShadow(self):
"""Get data system users in this system"""
return filter(lambda x: x[0] in self.sysThisMigrateUsers,self.getData())
return [x for x in self.getData() if x[0] in self.sysThisMigrateUsers]
def getNewProcessedData(self):
"""Get processed data migrate shadow in new system"""
dataThisShadow = self.getThisData()
dataNewShadow = self.getNewData()
namesNewShadow = map(lambda x: x[0], dataNewShadow)
namesNewShadow = [x[0] for x in dataNewShadow]
for data in dataThisShadow:
nameUser = data[0]
if nameUser in namesNewShadow:
dataNewShadow = filter(lambda x: x[0]!=nameUser, dataNewShadow)
namesNewShadow = map(lambda x: x[0], dataNewShadow)
dataNewShadow = [x for x in dataNewShadow if x[0] != nameUser]
namesNewShadow = [x[0] for x in dataNewShadow]
systemShadowNewData = self.getNewDataSystemShadow()
systemShadowThisData = self.getThisDataSystemShadow()
systemShadowNewNames = map(lambda x: x[0], systemShadowNewData)
systemShadowNewNames = [x[0] for x in systemShadowNewData]
for data in systemShadowThisData:
nameUser = data[0]
if nameUser in systemShadowNewNames:
systemShadowNewData = filter(lambda x: x[0]!=nameUser,
systemShadowNewData)
systemShadowNewNames = map(lambda x: x[0], systemShadowNewData)
systemShadowNewData = [x for x
in systemShadowNewData if x[0] != nameUser]
systemShadowNewNames = [x[0] for x in 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 = []
@ -257,8 +254,8 @@ class migrate:
minGid = 1000
minSysId = 1000
newUserGroups = ["audio", "cdrom", "cdrw", "games", "lp", "plugdev",
"scanner" "usb", "users", "video", "wheel"]
newUserGroups = ["audio", "cdrom", "cdrw", "games", "lp", "lpadmin",
"plugdev", "scanner" "usb", "users", "video", "wheel"]
def __init__(self, prefixNewSystem):
self.prefixNewSystem = prefixNewSystem
@ -268,50 +265,43 @@ class migrate:
def addThisUsersToGroups(self, users):
"""Add users to groups"""
thisGroupsData = self.objGroups.getData()
thisGroupsData = map(lambda x: (x[0],x[3].split(',')),
thisGroupsData)
thisGroupsData = [(x[0], x[3].split(',')) for x in thisGroupsData]
dataGroups = []
for data in self.dataGroups:
groupName = data[0]
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))
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))
if addUsers:
newUsersInGroup = data[3].split(',')
for user in addUsers:
if not user in newUsersInGroup:
newUsersInGroup.append(user)
data[3] = ','.join(filter(lambda x:x,newUsersInGroup))
data[3] = ','.join((x for x in newUsersInGroup if x))
dataGroups.append(data)
self.dataGroups = dataGroups
return self.dataGroups
def getNextUid(self):
"""get next uid"""
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))
listUid = [int(x[2]) for x in self.dataUsers
if self.objUsers._reNumb.match(x[2]) and self.minId <= int(x[2]) <= self.maxId]
if listUid:
return max(listUid)+1
return max(listUid) + 1
return self.minId
def getNextGid(self):
"""get next gid"""
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))
listGid = [int(x[2]) for x in self.dataGroups
if self.objUsers._reNumb.match(x[2]) and self.minGid <= int(x[2]) <= self.maxGid]
if listGid:
return max(listGid)+1
return max(listGid) + 1
return self.minGid
def isSystemUser(self, userName):
if filter(lambda x: x[0]==userName and int(x[2])<=self.minSysId,
self.dataUsers):
if [x for x in self.dataUsers
if (x[0] == userName and int(x[2]) <= self.minSysId)]:
return True
return False
@ -325,34 +315,33 @@ class migrate:
usersInGroup = data[3].split(',')
if not userName in usersInGroup:
usersInGroup.append(userName)
data[3] = ','.join(filter(lambda x:x,usersInGroup))
data[3] = ','.join((x for x in usersInGroup if x))
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 filter(lambda x: x[0]==userName, self.dataUsers):
raise MigrationError(_("User %s not found")%userName)
if not [x for x in self.dataUsers if x[0] == userName]:
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)
@ -363,80 +352,81 @@ class migrate:
def addUser(self, userName, userGroups, pwdHash):
"""Add user"""
# find user
if filter(lambda x: x[0]==userName, self.dataUsers):
if [x for x in self.dataUsers if x[0] == userName]:
return "EXISTS"
else:
strUid = str(self.getNextUid())
strGid = str(self.getNextGid())
groupName = userName
dataExistGroup = filter(lambda x: x[0]==groupName, self.dataGroups)
dataExistGroup = [x for x in self.dataGroups
if x[0] == groupName]
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 = map(lambda x: pathJoin(self.prefixNewSystem,x),
checkThisFiles)
checkNewFiles = [pathJoin(self.prefixNewSystem, x) for x in 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 = filter(notRead,checkThisFiles)
filesNotRead = [x for x in checkThisFiles if notRead(x)]
if filesNotRead:
raise MigrationError(_("Failed to read files") + _(": ") +
", ".join(filesNotRead))
filesNotWrite = filter(notWrite,checkNewFiles)
", ".join(filesNotRead))
filesNotWrite = [x for x in checkNewFiles if notWrite(x)]
if filesNotWrite:
raise MigrationError(_("Failed to write to files") + _(": ") +
", ".join(filesNotWrite))
", ".join(filesNotWrite))
# Check permissions backup files
checkNewBackupFiles = map(lambda x:pathJoin(self.prefixNewSystem,x+"-"),
checkThisFiles)
checkNewBackupFiles = (pathJoin(self.prefixNewSystem, x + "-") for x
in 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 = filter(notWriteBackup, checkNewBackupFiles)
filesNotWrite = [x for x in checkNewBackupFiles if notWriteBackup(x)]
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 = map(lambda x:(pathJoin(self.prefixNewSystem,x),
pathJoin(self.prefixNewSystem,x+"-")),
listFilesThisSystem)
listFiles = [(pathJoin(self.prefixNewSystem, x),
pathJoin(self.prefixNewSystem, x + "-")) for x
in listFilesThisSystem]
listData = [self.dataGroups, self.dataUsers, self.dataShadow]
allData = zip(listFiles,listData)
allData = zip(listFiles, listData)
for fileNames, data in allData:
buff = "\n".join(map(lambda x: ":".join(x), data)) + "\n"
buff = "\n".join((":".join(x) for x in data)) + "\n"
for fileName in fileNames:
FD = open(fileName, "w+")
FD = open(fileName, "w+")
FD.write(buff)
FD.close()
def createUserGuest(self):
if filter(lambda x: int(x[2])>=self.minSysId, self.dataUsers):
if [x for x in self.dataUsers if int(x[2]) >= self.minSysId]:
return True
else:
# add user guest
@ -445,58 +435,68 @@ class migrate:
pwdHash = encryptObj.getHashPasswd(pwd, "shadow_ssha256")
if pwdHash is False:
return False
if not self.addUser("guest", pwdHash):
if not self.addUser("guest", "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]))
users = list(set(map(lambda x:x[0],addUsersList)+existsMigrateUsers)-\
set(["root"]))
os.chown(homedir, int(userdata[2]), int(userdata[3]))
os.chmod(homedir, perms)
users = list(set([x[0] for x in addUsersList] + existsMigrateUsers) - {"root"})
try:
map(createHome,filter(lambda x:x[0] in users, self.dataUsers))
except Exception,e:
raise DistributiveError(
# 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(
_("Failed to create the user's home directory"))
def migrate(self, addUsersList=[], rootPwd="",
pwdUsersList=[], existsMigrateUsers=[]):
def migrate(self, addUsersList=None, rootPwd="",
pwdUsersList=None, existsMigrateUsers=None):
"""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
if not any(addUsersList):
addUsersList = []
migrateUsers = ["root"]+\
map(lambda x: x[0], addUsersList + pwdUsersList)
migrateUsers = (["root"] + [x[0] for x in addUsersList + pwdUsersList])
for existMigrUser in existsMigrateUsers:
if not existMigrUser in migrateUsers:
if existMigrUser not in migrateUsers:
migrateUsers.append(existMigrUser)
# add root to migrate users
dataUsers = self.objUsers.getNewProcessedData(migrateUsers)
dataGroups = self.objGroups.getNewProcessedData()
thisSystemUsers, newSystemUsers, newUsers, thisUsers =\
map(lambda x: map(lambda y: y[0],x), dataUsers)
thisSystemUsers, newSystemUsers, newUsers, thisUsers = \
[[y[0] for y in x] for x in 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):
self.prefixNewSystem = '/'
self.objGroups = migrateGroups(self.prefixNewSystem)
self.objUsers = migrateUsers(self.prefixNewSystem)
super().__init__('/')
def addUsers(self,*users_passwd):
def addUsers(self, *users_passwd):
"""Added users and groups to current system"""
if not self.checkPermFiles():
return False
@ -533,17 +533,16 @@ 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, pwdHash):
pwdHash = getHash(pwd, "shadow_ssha256")
if not self.addUser(userName, 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 = map(lambda x:x[0],
getDataInFile(fileName=migrateUsers.filePasswd,lenData=7))
self.dataUsers = [x[0] for x in getDataInFile(fileName=migrateUsers.filePasswd,lenData=7)]
return set(self.dataUsers) >= set(users)

@ -1,6 +1,6 @@
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# Copyright 2010-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2010-2016 Mir Calculate. 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,142 +15,153 @@
# limitations under the License.
import sys
from calculate.core.server.func import Action,Tasks
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
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.lib.utils.files import FilesError
from calculate.install.install import (MigrationError, TemplatesError,
InstallError,
AutopartitionError, DistributiveError)
from ..install import InstallError
setLocalTranslate('cl_install3',sys.modules[__name__])
setLocalTranslate('cl_install3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)
class ClInstallAction(Action):
"""
Установка системы
"""
# ошибки, которые отображаются без подробностей
native_error = (FilesError,MigrationError, TemplatesError,
InstallError, AutopartitionError, DistributiveError)
native_error = (FilesError, MigrationError, TemplatesError, VolumesError,
InstallError, AutopartitionError, DistributiveError)
successMessage = None
failedMessage = None
interruptMessage = None
# список задач для дейсвия
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)'
# список задач для действия
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",
},
# копирование прочих файлов
{'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",
# перемонтирование ntfs для определения windows
{'name': 'hdd:remount_ntfs',
'method': 'Install.remountNTFS()',
'essential': False,
},
# перемонтирование ntfs для определения windows
{'name':'hdd:remount_ntfs',
'method':'Install.remountNTFS()',
'essential':False,
# наложение шаблонов при установке на жесткий диск
{'name': 'hdd:apply_templates',
'message': __("Updating the configuration"),
# наложить шаблоны в установленный дистрибутив, включая clt шаблоны
# без использования фильтров по clt шаблонам
'method': 'Install.applyTemplates(cl_target,True,False,None)',
},
# наложение шаблонов при установке на жесткий диск
{'name':'hdd:apply_templates',
'message':__("Updating the configuration"),
# наложить шаблоны в установленный дистрибутив, включая clt шаблоны
# без использования фильтров по clt шаблонам
'method':'Install.applyTemplates(cl_target,True,False,None)',
# наложение шаблонов при 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'
},
# наложение шаблонов при 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)",
# наложение шаблонов при установке на 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"
},
# перенос пользователей
{'name':'hdd:user_migrate',
'message':__("Migrating users"),
'method':'Install.userMigrate(cl_target,cl_migrate_data,'
'cl_migrate_root_pwd)',
# подключить точки монтирования bind
{'name': 'hdd:mount_bind',
'message': __("Post-install configuration"),
'method': "Install.mountBind(cl_target)",
},
# подготовка загрузчика
{'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': '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 "
"now to complete the installation?"),
'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')
'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')
}
]
]

@ -1,6 +1,6 @@
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# Copyright 2010-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2010-2016 Mir Calculate. 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,73 +15,84 @@
# limitations under the License.
import sys
from calculate.core.server.func import Action,Tasks
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
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.lib.utils.files import FilesError
from calculate.lib.utils.portage import isPkgInstalled
from calculate.install.install import (MigrationError, TemplatesError,
InstallError,
AutopartitionError, DistributiveError)
from ..install import InstallError
from ..variables.autopartition import AutopartitionError
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")
addon_tasks = [
prev_tasks = [
# проверить и настроить параметры для nvidia драйвера
{'name':'check_video',
'message':__("Checking the video driver"),
'method':'Install.checkVideoDriver()',
'condition': lambda:isPkgInstalled('xorg-server')
},
{'name':'setup_opengl',
'message':__("Configuring OpenGL"),
'method':'Install.setupOpenGL()',
'condition': lambda:isPkgInstalled('xorg-server')
{'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':'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')
}
]
]
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 = [
{'name':'apply_templates',
'message':self.templateTaskMessage,
# наложить шаблоны на текущий дистрибутив, включая clt шаблоны
# без использования фильтров по clt шаблонам
'method':'Install.applyTemplates(cl_source,cl_template_clt_set,'\
'cl_merge_set,None)',
}]
# список задач для действия
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)',
}]
# выполнить дополнительные задачи
self.tasks.extend(self.addon_tasks)
Action.__init__(self)
@ -91,29 +102,50 @@ 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):
"""
Действие для настройки аудио параметров
@ -123,6 +155,7 @@ class ClSetupNetworkAction(ClSetupSystemAction):
successMessage = __("Network settings configured!")
failedMessage = __("Failed to configure the network settings!")
class ClSetupSessionAction(ClSetupSystemAction):
"""
Действие для настройки пользовательских параметров
@ -132,6 +165,7 @@ class ClSetupSessionAction(ClSetupSystemAction):
successMessage = __("Session settings configured!")
failedMessage = __("Failed to configure the session settings!")
class ClSetupBootAction(ClSetupSystemAction):
"""
Действие для настройки параметров загрузки
@ -140,27 +174,19 @@ 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'
},
# изменить 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))
},
]
{'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'
},
]

@ -1,6 +1,6 @@
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2008-2016 Mir Calculate. 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,20 +18,31 @@ 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 process, STDOUT, getProgPath, readFile
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.common import (getVideoFromXorgLog,
getVideoFromXorgConf, getVideoFromCmdLine,
getAvailableVideo, getValueFromCmdLine,
getCompositeFromXorgconf, getVideoFromModules,
getVideoFromVendor, getInstalledVideo)
from calculate.install.distr import DistributiveError
getVideoFromXorgConf,
getVideoFromCmdLine,
getAvailableVideo, getValueFromCmdLine,
getCompositeFromXorgconf,
getVideoFromModules,
getVideoFromVendor, getInstalledVideo,
CmdlineParams)
from calculate.lib.utils.video import get_edid_data, EdidInfoError, EdidInfo
from ..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):
"""
@ -39,13 +50,16 @@ class VideoVariable(Variable):
"""
xorg_need = True
default_video = "default"
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")
}
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)")),
])
def uncompatible(self):
"""
@ -54,16 +68,19 @@ class VideoVariable(Variable):
if self.Get('os_install_root_type') == 'flash':
return \
_("Video configuration unavailable for Flash install")
if self.Get('os_install_x11_server_set') == 'off' and self.xorg_need:
if (self.Get('install.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",
@ -73,28 +90,31 @@ class ResolutionVariable(VideoVariable):
"1600x900", "1600x1200", "2048x1152", "2560x1440",
"2560x1600"]
if self.fbres:
return map(lambda x:"%s-32"%x,
resolutions)
return ["%s-32" % x for x in 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 VariableOsInstallX11Resolution(ResolutionVariable):
class VariableOsInstallX11ResolutionPreferred(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")
@ -103,34 +123,64 @@ class VariableOsInstallX11Resolution(ResolutionVariable):
def get(self):
# get resolution from xorg.log
res = self.Get('os_x11_resolution')
if res or self.Get('os_install_root_type') in ('livecd','usb-hdd'):
if res:
return res
else:
return self.choice()[-1]
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
class VariableOsInstallX11VideoAvailable(VideoVariable):
"""
Get available (already installed or installable drivers
"""
type = "list"
supported = ["nvidia", "fglrx", "nouveau", "intel", "radeon"]
# supported = ["nvidia", "fglrx", "amdgpu", "nouveau", "intel", "radeon"]
supported = ["nvidia", "amdgpu","modesetting",
"nouveau", "intel", "radeon", "vesa"]
def get(self):
image = self.Get('cl_image')
if image:
with image as distr:
with image:
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 as e:
except DistributiveError:
pass
return []
def humanReadable(self):
return map(lambda x: self.driver_names.get(x, x), self.Get())
return [self.driver_names.get(x, x) for x in self.Get()]
class VariableOsX11KmsVideoDrv(ReadonlyVariable):
@ -138,7 +188,7 @@ class VariableOsX11KmsVideoDrv(ReadonlyVariable):
Список KMS драйверов
"""
type = "list"
value = ["radeon", "intel", "nouveau"]
value = ["radeon", "intel", "nouveau", "amdgpu", "modesetting"]
class VariableOsInstallX11VideoDrv(VideoVariable):
@ -153,13 +203,22 @@ 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.Get('os_x11_kms_video_drv') + [self.default_video]
return map(lambda x: (x, self.driver_names.get(x, x)), values)
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]]
def get(self):
if self.Get('os_install_x11_server_set') == 'on':
@ -169,52 +228,54 @@ 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,('/',)),
(getVideoFromModules,()),
(getVideoFromCmdLine,()),
(getVideoFromVendor,(self.Get('hr_video'),list_video)))
for func,args in methods:
methods = ((getVideoFromXorgLog, ('/', list_video)),
(getVideoFromXorgConf, ('/',)),
(getVideoFromCmdLine, ()),
(getVideoFromModules, ()),
(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 map(lambda x:x[0], self.choice()):
videoSysPath = path.join("/sys/module",drv,"refcnt")
refcnt = readFile(videoSysPath).strip()
for drv in (x[0] for x in self.choice()):
refcnt = device.sysfs.read(
device.sysfs.Path.Module, drv, "refcnt").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.Get('os_x11_kms_video_drv') + [self.default_video]
availDrivers = self.nox_video_drivers()
if not value in availDrivers:
raise VariableError("Only %s drivers are available" %
",".join(availDrivers))
@ -228,6 +289,13 @@ class VariableOsInstallX11VideoDrv(VideoVariable):
_("Video configuration unavailable for Flash install")
return ""
class VariableOsInstallX11VideoDrvPrev(VariableOsInstallX11VideoDrv):
"""
Предыдущее значение os_install_x11_videodrv
"""
class VariableHrVideoId(ReadonlyVariable):
"""
BusID of video card
@ -235,6 +303,7 @@ class VariableHrVideoId(ReadonlyVariable):
"""
value = ""
class VariableOsInstallX11Composite(VideoVariable):
"""
on/off composite
@ -248,14 +317,18 @@ class VariableOsInstallX11Composite(VideoVariable):
def get(self):
"""On/off composite"""
defaultCompositeOn = ("nvidia","intel","fglrx","nouveau","radeon")
composite = getValueFromCmdLine("calculate",5)
videodrv = getValueFromCmdLine("calculate",4)
defaultCompositeOn = ("nvidia", "intel", "fglrx", "amdgpu",
"modesetting",
"nouveau", "radeon", "default")
composite = getValueFromCmdLine(CmdlineParams.Calculate,
CmdlineParams.Composite)
videodrv = getValueFromCmdLine(CmdlineParams.Calculate,
CmdlineParams.Video)
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
@ -271,6 +344,31 @@ 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
@ -280,20 +378,174 @@ 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")
FBIOGET_VSCREENINFO = 0x4600
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"
class VariableClInstallScaling(Variable):
def get(self):
"""Get current framebuffer resolution"""
dpi = self.Get('cl_install_dpi')
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):
if dpi:
dpi = int(dpi)
if dpi > 100:
return "hi"
except ValueError:
pass
return "1024x768"
return "normal"

@ -1,6 +1,6 @@
#-*- coding: utf-8 -*-
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2008-2016 Mir Calculate. 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.
import action
import disk
import locale
import linux
import distr
import kernel
import net
import system
import X11
import lvm
import autopartition
import audio
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
section = "install"

@ -1,6 +1,6 @@
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2008-2016 Mir Calculate. 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,30 +14,33 @@
# 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,
ActionVariable)
from calculate.lib.datavars import ActionVariable
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
setLocalTranslate('cl_install3', sys.modules[__name__])
ServerSetup = "server_setup"
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 ("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 (ServerSetup, "sync",
"domain", "undomain",)
and self.Get('cl_merge_pkg')):
return "on"
return "off"
class VariableAcInstallLive(ActionVariable):
"""
Action variable which has value "on"
@ -46,72 +49,96 @@ 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 ("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 (ServerSetup,
"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):
clSetup = self.Get('cl_setup')
if cl_action == "merge" and clSetup:
def action(self, cl_action):
cl_setup = self.Get('cl_setup')
if cl_action == "merge" and cl_setup:
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-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2008-2016 Mir Calculate. 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,16 +14,98 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import re
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.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 calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
class VariableOsAudioData(ReadonlyTableVariable):
"""
@ -32,17 +114,35 @@ class VariableOsAudioData(ReadonlyTableVariable):
source = ['os_audio_id',
'os_audio_name']
def get(self,hr=False):
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
data = readFile('/proc/asound/cards')
cards = re.findall('^\s*(\d+).*\n\s+(\S.*) at .*$',data,re.M)
cards = re.findall('^\s*(\d+).*\s-\s(.+)\n\s+\S.* at .*$',
data, re.M)
if cards:
return map(list, cards)
return list(self.generate_cards(cards))
else:
return [[]]
setValue = Variable.setValue
class VariableOsAudioId(FieldValue,ReadonlyVariable):
class VariableOsAudioId(FieldValue, ReadonlyVariable):
"""
Order Id of audio card
"""
@ -50,7 +150,8 @@ class VariableOsAudioId(FieldValue,ReadonlyVariable):
source_variable = "os_audio_data"
column = 0
class VariableOsAudioName(FieldValue,ReadonlyVariable):
class VariableOsAudioName(FieldValue, ReadonlyVariable):
"""
Name of audio card
"""
@ -58,55 +159,109 @@ class VariableOsAudioName(FieldValue,ReadonlyVariable):
source_variable = "os_audio_data"
column = 1
class VariableOsAudioDefaultSet(ReadonlyVariable):
class VariableOsAudioCardDefault(Variable):
"""
Force write in config 0
Идентификатор карты по умолчанию
"""
type = "bool"
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 ""
class VariableOsAudioDeviceDefault(Variable):
"""
Номер устройства по умолчанию
"""
def get(self):
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'
audio_default = self.Get('os_audio_default')
if audio_default and audio_default != "none":
return self.Get('os_audio_default').split(',')[1]
return ""
class VariableOsAudioCurrent(ReadonlyVariable):
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):
"""
Current default audio card
"""
def get(self):
defaultCardRe = re.compile('defaults.ctl.card\s+(\d+)')
entry = defaultCardRe.search(readFile('/etc/asound.conf'))
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 entry.groups()[0]
res = self.Select('os_audio_id',where='os_audio_name',
notlike='HDMI',limit=1)
return res or '0'
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 ""
class VariableOsAudioDefault(Variable):
"""
Current default audio card
"""
type = "choice"
opt = ['--audio']
type = "choice"
opt = ['--card']
metavalue = "CARD"
def init(self):
self.label = _("Default audio card")
self.help = _("set the default audio")
def get(self):
return self.Get('os_audio_current')
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"
def choice(self):
data = self.Get('os_audio_data')
if data and data[0]:
return self.Get('os_audio_data')
return []
return [("none", _("Not available"))]
def uncompatible(self):
"""
@ -115,6 +270,5 @@ 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-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2008-2016 Mir Calculate. 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,39 +20,48 @@ from os import path
import re
import operator
from operator import itemgetter
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.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.variables.linux import Linux
from calculate.install.distr import (Distributive,PartitionDistributive,
DirectoryDistributive,
ScratchPartitionDistributive,DistributiveError,FlashDistributive,
MultiPartitions,PxeDistributive)
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.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
class DistroRepository(Linux):
contentCache = {}
marches = ['i686','x86_64']
marches = ['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+",
'march':"|".join(marches),
'ext':"|".join(extensiton)
}, re.X)
def _getDistrInfo(self,filename):
{'name': "[a-z0-9]+",
'ver': r"(\d+\.)*\d+",
'ser': r"\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):
@ -69,8 +78,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":
@ -84,40 +93,43 @@ class DistroRepository(Linux):
version=linuxVer,
build=linuxBuild)
def _getAvailableShortnames(self,dirs):
def _getAvailableShortnames(self, dirs):
"""Get available distributives shortnames"""
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):
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):
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:
@ -125,119 +137,123 @@ class DistroRepository(Linux):
# check filter conditions
if system and systemByName(d['os_linux_shortname']) != system:
return False
if not "os_linux_shortname" in d or not "os_linux_ver" in d:
if "os_linux_shortname" not in d or "os_linux_ver" not 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 filter(lambda x:not path.isdir( path.join(pathname,x)),
listDirectory(pathname))
return [x for x in listDirectory(pathname) if not path.isdir(path.join(pathname, x))]
# get lists files in directories
allFiles = map(lambda x: map(lambda y: path.join(x,y),
listdistr(x)),
dirs)
allFiles = [[path.join(x, y) for y in listdistr(x)] for x in dirs]
# filter distributives
return filter(distfilter,
# join files lists to one list
reduce(lambda x,y: x + y,
allFiles, []))
# join files lists to one list
return [x for x in reduce(lambda x, y: x + y, allFiles, []) if distfilter(x)]
def extcomparator(self,*exts):
@staticmethod
def extcomparator(ext1, ext2):
"""Compare extensions"""
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):
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):
"""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:
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=[]):
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=()):
"""Get list available distributives"""
if shortname:
shortname = shortname.lower()
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=[]):
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=()):
"""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 = 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)
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]
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 == True:
elif hardened is True:
hardened = "-hardened"
elif hardened == False:
elif hardened is 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):
@ -249,7 +265,8 @@ class VariableClImage(ReadonlyVariable):
def get(self):
"""Get image file from distributive repository"""
try:
if not self.Get('cl_action') in ('system','prepare'):
action = self.Get('cl_action')
if not action in ('system',):
return Distributive.fromFile('/')
filename = self.Get('cl_image_filename')
if filename:
@ -264,7 +281,8 @@ class VariableClImage(ReadonlyVariable):
return filename.getType()
return filename
class VariableClImageFilename(Variable,DistroRepository):
class VariableClImageFilename(DistroRepository, Variable):
"""
Distributive image filename
"""
@ -272,6 +290,7 @@ class VariableClImageFilename(Variable,DistroRepository):
element = 'file'
metavalue = "IMAGE"
opt = ['--iso']
check_after = ["os_install_root_type"]
untrusted = True
def init(self):
@ -283,44 +302,55 @@ class VariableClImageFilename(Variable,DistroRepository):
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
@ -328,33 +358,32 @@ class VariableClImageFilename(Variable,DistroRepository):
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(map(lambda x:(x,
self.humanImageName(self._getDistrInfo(x),x)),
distros),key=itemgetter(1))
return sorted(((x, self.humanImageName(self._getDistrInfo(x), x)) for x in distros), key=itemgetter(1))
class VariableClImageArchMachine(Variable,DistroRepository):
class VariableClImageArchMachine(DistroRepository, Variable):
"""
Filter by architecture
"""
@ -362,73 +391,83 @@ class VariableClImageArchMachine(Variable,DistroRepository):
type = 'choice'
opt = ['--march']
metavalue = "ARCH"
available_arch = ["i686","x86_64"]
available_arch = ["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(Variable,Linux,DistroRepository):
class VariableClImageLinuxShortname(DistroRepository, Variable):
"""
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"))]+\
sorted(map(lambda x:(x,self.getFullNameByShort(x)),
self.dictLinuxName.keys()),
key=itemgetter(1))
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"),
]
def humanReadable(self):
return self.Get() or _("Not used")
class VariableClImageLinuxVer(Variable,DistroRepository):
class VariableClImageLinuxVer(DistroRepository, Variable):
"""
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(Variable,DistroRepository):
class VariableClImageLinuxBuild(DistroRepository, Variable):
"""
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
@ -448,22 +487,26 @@ class VariableClImagePath(ReadonlyVariable):
livedistr = ['/mnt/livecd']
# standard livecd
else:
livedistr = ['/run/initramfs/squashfs',
'/run/initramfs/live',
'/mnt/cdrom']
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]
else:
livedistr = []
# search all partition for source installation distributive
rootDev = self.Get('os_install_root_dev')
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'))))
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]
# add to standard path
return filter(path.exists,
['/var/calculate/remote/linux',
'/var/calculate/linux'] + livedistr)
return [x for x in ['/var/calculate/remote/linux',
'/var/calculate/linux'] + livedistr if path.exists(x)]
class VariableClSource(ReadonlyVariable):
"""
@ -474,11 +517,13 @@ 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',
@ -488,101 +533,145 @@ 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:
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":
raise VariableError("Scratch is not supported")
if 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='/mnt/install',
check=True,fileSystem=fileSystem,
rootLabel=rootLabel,
isFormat=self.isTrue(isFormat),
systemId=systemId,
partitionTable=partTable)
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'))
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:
return imageData.get('os_linux_build', '')
except Exception:
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-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2008-2016 Mir Calculate. 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,20 +18,26 @@ import os
import sys
import re
from os import path
from calculate.lib.datavars import Variable,VariableError,ReadonlyVariable
from calculate.lib.utils.files import (
typeFile,process,listDirectory,MAGIC_SYMLINK,MAGIC_COMPRESS)
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.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
_ = lambda x: x
setLocalTranslate('cl_install3', sys.modules[__name__])
from operator import itemgetter
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 calculate.lib.utils.files import readLinesFile
from calculate.lib.utils.common import (getKernelUid, getTupleVersion,
getValueFromCmdLine, CmdlineParams)
from itertools import *
from calculate.install.distr import DistributiveError
from ..distr import DistributiveError
class VariableOsInstallKernelScheduler(Variable):
"""
@ -45,30 +51,50 @@ 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':
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"
return self.get_default()
else:
currentScheduler = getValueFromCmdLine('elevator',0)
if currentScheduler in map(lambda x:x[0],self.choice()):
currentScheduler = getValueFromCmdLine(
CmdlineParams.IOScheduler)
if currentScheduler in (x[0] for x in self.choice()):
return currentScheduler
return "cfq"
return self.Get('os_install_kernel_schedule_default')
def choice(self):
schedulers = [("deadline","Deadline"),("cfq","CFQ"),("noop","No-op")]
if self.Get('os_install_kernel_bfq_set') == 'on':
return schedulers + [("bfq","BFQ")]
else:
return schedulers
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
def uncompatible(self):
"""
@ -77,141 +103,325 @@ class VariableOsInstallKernelScheduler(Variable):
if self.Get('os_install_root_type') == 'flash':
return _("I/O scheduler unavailable for Flash install")
class VariableOsInstallKernelBfqSet(ReadonlyVariable):
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):
"""
Available BFQ in kernel
Install config kernel filename
"""
type = "bool"
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'
def get(self):
image = self.Get('cl_image')
if image:
with image as distr:
with image:
try:
distrPath = image.getDirectory()
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"
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"
return "off"
class VariableOsInstallKernelAttr(Variable):
"""
Install kernel attributes
"""
def get(self):
# 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
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())
class VariableOsInstallKernelResume(ReadonlyVariable):
"""
Install kernel resume
"""
def get(self):
"""install kernel resume parameter"""
for dev, install in zip(self.Get('os_install_disk_use'),
self.Get('os_install_disk_mount')):
for dev, partuuid, install in zip(self.Get('os_install_disk_use'),
self.Get('os_install_disk_partuuid'),
self.Get('os_install_disk_mount')):
if install == "swap":
if self.Get('os_install_linux_system') == 'desktop':
return \
"tuxonice tuxonice_resume=%s real_resume=%s"%(dev,dev)
if self.Get('os_install_kernel_tuxonice_set') == 'on':
return "tuxonice tuxonice_resume=%s real_resume=%s" % (
dev, dev)
else:
return "real_resume=%s"%dev
if partuuid:
return "resume=PARTUUID=%s" % partuuid
else:
return "resume=%s" % dev
return ""
class KernelHelper:
class KernelHelper(VariableInterface):
"""
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 = 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=""):
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=""):
"""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 == None:
if typeKernelFile is 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.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))
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))]
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 = \
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)))
# 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]]]
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
"""
@ -221,18 +431,20 @@ 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'),
@ -241,43 +453,63 @@ 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 = map(lambda x:x.partition('=')[2].strip("\n '\""),
filter(lambda x:x.startswith('modules_3'),
readLinesFile('/etc/conf.d/modules')))
cpufreqmods = [x.partition('=')[2].strip("\n '\"") for x
in readLinesFile('/etc/conf.d/modules') if x.startswith('modules_3')]
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-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2008-2016 Mir Calculate. 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,25 +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.linux import (Linux,VariableOsLinuxName,
VariableOsLinuxSystem,VariableOsLinuxSubname)
from calculate.lib.datavars import ReadonlyVariable, VariableInterface
from calculate.lib.variables.linux import Linux
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
class InstallLinux(Linux):
def __getFromImageOrCurrent(self,currentVar):
setLocalTranslate('cl_install3', sys.modules[__name__])
class InstallLinux(Linux, VariableInterface):
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 ""
@ -48,39 +47,55 @@ class InstallLinux(Linux):
"""Get by distroinfo or current info"""
return self.__getFromImageOrCurrent(self.current_variable)
class VariableOsInstallLinuxShortname(InstallLinux,ReadonlyVariable):
class VariableOsInstallChrootableSet(InstallLinux, ReadonlyVariable):
"""Можно ли выполнить chroot в систему"""
current_variable = "os_chrootable_set"
class VariableOsChrootableSet(ReadonlyVariable):
"""Можно ли выполнить chroot в систему"""
type = "boolean"
value = "on"
class VariableOsInstallLinuxShortname(InstallLinux, ReadonlyVariable):
"""Shortname of system"""
current_variable = "os_linux_shortname"
class VariableOsInstallLinuxVer(InstallLinux,ReadonlyVariable):
"""Shortname of system"""
class VariableOsInstallLinuxVer(InstallLinux, ReadonlyVariable):
"""Version of system"""
current_variable = "os_linux_ver"
class VariableOsInstallLinuxBuild(InstallLinux,ReadonlyVariable):
"""Shortname of system"""
class VariableOsInstallLinuxBuild(InstallLinux, ReadonlyVariable):
"""Build of system"""
current_variable = "os_linux_build"
class VariableOsInstallArchMachine(InstallLinux,ReadonlyVariable):
"""Shortname of system"""
class VariableOsInstallArchMachine(InstallLinux, ReadonlyVariable):
"""Arch of system"""
current_variable = "os_arch_machine"
class VariableOsInstallLinuxFiles(InstallLinux,ReadonlyVariable):
"""Shortname of system"""
class VariableOsInstallLinuxFiles(InstallLinux, ReadonlyVariable):
"""Files num in 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-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2008-2016 Mir Calculate. 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,27 @@
# 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.common import getValueFromCmdLine, getValueFromConfig
from pytz import timezone,country_timezones,UnknownTimeZoneError
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 datetime import datetime
from operator import itemgetter
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
from calculate.lib.cl_lang import setLocalTranslate, _
class LocaleVariable(ReadonlyVariable,Locale):
setLocalTranslate('cl_install3', sys.modules[__name__])
class LocaleVariable(ReadonlyVariable, Locale):
"""
Locale variables not using for flash installation
"""
def uncompatible(self):
"""
Network setting up unavailable for flash installation
@ -41,6 +44,7 @@ class LocaleVariable(ReadonlyVariable,Locale):
_("Locale configuration unavailable for Flash install")
return ""
class VariableOsInstallLinguas(LocaleVariable):
"""
Current LINGUAS value
@ -49,111 +53,140 @@ class VariableOsInstallLinguas(LocaleVariable):
def get(self):
def get_linguas(lines):
linguas = map(lambda x:x.strip().rpartition('=')[-1].strip('"\''),
filter(lambda x: x.startswith("LINGUAS="),
lines))
linguas = [x.strip().rpartition('=')[-1].strip('"\'') for x
in lines if x.startswith("LINGUAS=")]
return linguas[-1] if linguas else ""
makeconf = '/etc/make.conf'
infocommand = ['emerge','--info']
defaultLinguas = "bg en de es fr it pl pt_BR ru uk"
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"
# get linguas from make.conf, emerge --info or default
curlanguage = self.Get('os_install_locale_language')
return get_linguas(readLinesFile(makeconf)) or \
" ".join(filter(lambda x:x=="en" or x==curlanguage,
get_linguas(
process(*infocommand).readlines() or "").split())) or \
defaultLinguas
" ".join((x for x in get_linguas(process(*infocommand).readlines() or "").split() if x == "en" or x == curlanguage)) or defaultLinguas
class VariableOsInstallLocaleConsolefont(LocaleVariable):
"""
Consolefont for locale
"""
def get(self):
return self.getFieldByKeymap("consolefont",
self.Get('os_install_locale_keymap'))
return self.getConsolefont(self.Get('os_install_locale_keyboard_layout'))
class VariableOsInstallLocaleKeymap(LocaleVariable):
"""
Keymap of locale (used for /etc/conf.d/keymaps)
"""
def get(self):
# 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"))
return self.getKeymap(self.Get('os_install_locale_keyboard_layout'))
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.getFieldByKeymap("dumpkeys_charset",
self.Get('os_install_locale_keymap'))
return self.getDumpkeys_charset(
self.getKeyboardLayout(
keymap=self.Get('os_install_locale_keymap')))
else:
return self.getFieldByLang("dumpkeys_charset",
self.Get('os_install_locale_lang'))
return self.getDumpkeys_charset(
self.Get('os_install_locale_keyboard_layout'))
class VariableOsInstallLocaleLocale(LocaleVariable):
"""
Locale (at example: ru_RU.UTF-8)
Locale (at example: ru_RU.utf8)
"""
def get(self):
"""locale (example: ru_RU.UTF-8)"""
return self.getFieldByLang("locale",
self.Get('os_install_locale_lang'))
"""locale (example: ru_RU.utf8)"""
return self.getLocale(self.Get('os_install_locale_lang'))
class VariableOsInstallLocaleLang(LocaleVariable):
"""
Full language (at example: ru_RU)
"""
mode = 'w'
metavalue = "LANG"
metavalue = "LOCALE"
type = 'choice'
opt = ["--lang","-l"]
opt = ["--locale", "-l"]
def init(self):
self.label = _("Language")
self.help = _("set the language")
self.label = _("Locale")
self.help = _("set the locale")
def get(self):
"""lang (example: ru_RU)"""
return self.Get('os_locale_lang')
def choice(self):
return sorted(zip(self.Get('os_lang'),
map(str,self.Get('os_lang',humanreadable=True))),key=itemgetter(1))
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))))
class VariableOsInstallLocaleLanguage(LocaleVariable):
"""
Short language (at example ru)
"""
def get(self):
return self.getFieldByLang("language",
self.Get('os_install_locale_lang'))
return self.getLanguage(self.Get('os_install_locale_lang'))
class VariableOsInstallLocaleXkb(LocaleVariable):
"""
Keyboard layout for X server
"""
def get(self):
return self.getFieldByLang("xkblayout",
self.Get('os_install_locale_lang'))
return self.getXkblayout(self.Get('os_install_locale_keyboard_layout'))
class VariableOsInstallLocaleXkbname(LocaleVariable):
"""
Keyboard layout name for X server
"""
def get(self):
localeXkb = self.Get("os_install_locale_xkb")
if localeXkb:
@ -169,6 +202,7 @@ class VariableOsInstallClockTimezone(LocaleVariable):
type = 'choiceedit'
metavalue = "TIMEZONE"
opt = ["--timezone"]
locale_varname = 'os_install_locale_lang'
def init(self):
self.label = _("Timezone")
@ -177,154 +211,186 @@ 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/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"]
"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')))
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('os_install_locale_lang').split('_')[1]
nativeTZ = map(lambda x:x.encode('utf-8'),
country_timezones[lang])
lang = self.Get(self.locale_varname).split('_')[1]
nativeTZ = [x for x in country_timezones[lang]]
source = nativeTZ + ["---"] + \
sorted(filter(lambda x:not x in nativeTZ,source),
key=sortkey)
except (KeyError,IndexError) as e:
sorted([x for x in source if not x in nativeTZ], 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 = ["--clocktype"]
metavalue = "CLOCKTYPE"
opt = ["--hwclock"]
metavalue = "CLOCK"
fallback_value = "local"
def init(self):
self.label = _("Clock type")
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
def get(self):
"""type of clock (UTC or local)"""
clockTypeFile = ['/etc/conf.d/clock','/etc/conf.d/hwclock']
# в первую очередь смотрим на параметры загрузки системы
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']
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 "local"
# запасное значение
return self.fallback_value
def choice(self):
return ["local","UTC"]
return ["local", "UTC"]

@ -1,6 +1,6 @@
#-*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
# Copyright 2008-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2008-2016 Mir Calculate. 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,52 +14,47 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
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.datavars import (Variable, VariableInterface,
ReadonlyVariable, ReadonlyTableVariable,
FieldValue, HumanReadable)
from calculate.lib.utils import device
from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
class LvmHelper:
setLocalTranslate('cl_install3', sys.modules[__name__])
class LvmHelper(VariableInterface):
def getLvmData(self):
"""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
for vg, lv, pv in device.lvm.pvdisplay_full():
yield lv, vg, pv
#######################################################
# Devices variables
#######################################################
class VariableOsLvmData(ReadonlyTableVariable,LvmHelper):
class VariableOsLvmData(ReadonlyTableVariable, LvmHelper):
"""
Information about disk devices
Information about LVM
"""
source = ['os_lvm_lvname',
'os_lvm_vgname',
'os_lvm_pvname']
'os_lvm_pvname',
'os_lvm_pvname_parent'
]
def get(self,hr=False):
def get(self, hr=HumanReadable.No):
"""LVM hash"""
return list(self.getLvmData()) or [[]]
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 [[]]
setValue = Variable.setValue
class VariableOsLvmLvname(FieldValue,ReadonlyVariable):
class VariableOsLvmLvname(FieldValue, ReadonlyVariable):
"""
Logical volumes names
"""
@ -67,7 +62,8 @@ class VariableOsLvmLvname(FieldValue,ReadonlyVariable):
source_variable = "os_lvm_data"
column = 0
class VariableOsLvmVgname(FieldValue,ReadonlyVariable):
class VariableOsLvmVgname(FieldValue, ReadonlyVariable):
"""
Volume groups names
"""
@ -75,10 +71,19 @@ 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-2013 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2010-2016 Mir Calculate. 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,285 +14,413 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import sys, time, os
import sys
from calculate.lib.datavars import VariableError,DataVarsError,DataVars
from calculate.install.install import InstallError
from calculate.install.distr import DistributiveError
from calculate.lib.datavars import VariableError, DataVarsError
from .distr import DistributiveError
import install
from calculate.lib.cl_lang import setLocalTranslate,getLazyLocalTranslate
setLocalTranslate('cl_install3',sys.modules[__name__])
from . 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.install.utils.cl_install import ClInstallAction
from calculate.install.utils.cl_setup import (ClSetupAudioAction,
ClSetupLocaleAction,ClSetupVideoAction,ClSetupSystemAction,
ClSetupBootAction,ClSetupNetworkAction,
ClSetupSessionAction)
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)
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,
DataVarsError,install.InstallError),
'datavars': "install",
'native_error': (VariableError, DistributiveError, VolumesError,
DataVarsError, install.InstallError),
# значения по умолчанию для переменных этого метода
'setvars':{'cl_action!':'system','cl_dispatch_conf':'usenew'},
'setvars': {'cl_action!': 'system',
'cl_chroot_status!': 'off', 'cl_install_type': 'hdd',
'cl_dispatch_conf': 'usenew'},
# описание груп (список лямбда функций)
'groups': [
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(_("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(_("Update"),
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")}},
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")}},
# установка на Flash
{
'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"))]},
'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")}},
# PXE установка
{
'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': "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':"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_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':'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"))]},
# настройка сети
'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':'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_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_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',
# настройка видео
'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',
'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_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_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_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_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"))]}
]
# настройка тем
'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"))]}
]

@ -3,7 +3,7 @@
# setup.py --- Setup script for calculate-install
# Copyright 2010 Calculate Ltd. http://www.calculate-linux.org
# Copyright 2010-2016 Mir Calculate. 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,20 +23,61 @@ __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',0755)]),
('/usr/bin',[('bin/xautologin',0755)]),
data_files += [('/etc/init.d', [('data/calculate',0o755)]),
('/usr/bin',[('bin/xautologin',0o755)]),
('/usr/share/calculate/doc', ['data/handbook-en.html',
'data/handbook-ru.html',
'data/handbook-es.html',
'data/handbook-fr.html']),
('/bin',[('bin/bashlogin',0755)])]
'data/handbook-ru.html']),
('/usr/libexec/calculate', [('data/cl-video-install', 0o755)]),
('/bin',[('bin/bashlogin',0o755)])]
packages = [
"calculate."+str('.'.join(root.split(os.sep)[1:]))

Loading…
Cancel
Save