Практическое применение Linux Deploy на десктопах
Несмотря на то, что изначально Linux Deploy задумывался как приложение для Android, со временем появляются и другие варианты его применения. С появлением Linux Deploy CLI стал доступен ряд возможностей, открывающих новые сферы применения этого инструмента.
Linux Deploy CLI — это приложение с интерфейсом для командной строки, предназначенное для автоматизации процесса установки, конфигурирования и запуска GNU/Linux дистрибутивов внутри контейнера chroot. Приложение может работать как в обычных десктопных Linux-дистрибутивах, так и на мобильных платформах, основанных на ядре Linux, при условии соблюдения необходимых зависимостей (все зависимости могут быть собраны статически). Приложения из Linux-дистрибутива запускаются в chroot окружении, работают параллельно с основной системой и сопоставимы с ней по скорости. Поскольку работа Linux Deploy базируется на системном вызове ядра Linux, то в роли «гостевых» систем могут выступать только дистрибутивы Linux.
Приложение может работать в двух режимах: с правами суперпользователя (chroot) и без них (proot). В обычном режиме доступны все поддерживаемые типы установки: установка в файл, на раздел диска (логический диск), в POSIX совместимую директорию и в оперативную память (tmpfs). В режиме proot доступна установка только в директорию, а также появляется ряд ограничений:
- все пользователи внутри контейнера имеют полный доступ ко всей файловой системе контейнера, а владельцем всех файлов и каталогов является текущий пользователь;
- нет доступа к привилегированным операциям с системой, например, не работает ping, ulimit и т.п.;
- приложения могут работать только с номерами сетевых портов выше 1024;
- если приложение в своей работе использует системный вызов chroot, то его необходимо запускать через специальную утилиту fakechroot, например fakechroot /usr/sbin/sshd -p 2222.
Приложение поддерживает автоматическую установку (базовой системы) и начальную настройку дистрибутивов Debian, Ubuntu, Kali Linux, Arch Linux, Fedora, CentOS, Gentoo, openSUSE и Slackware. Установка Linux-дистрибутива осуществляется по сети с официальных зеркал в интернете. Также поддерживается импорт любой другой системы из заранее подготовленного rootfs-ахрива в формате tar.gz, tar.bz2 или tar.xz. Приложение позволяет подключаться к консоли установленной системы (контейнеру), а также запускать и останавливать приложения внутри контейнера (есть поддержка различных систем инициализации и собственных сценариев автозапуска). Каждый вариант установки сохраняется в отдельный конфигурационный файл, который отвечает за настройку каждого контейнера. При необходимости, контейнеры можно запускать параллельно. Можно экспортировать конфигурацию и сам контейнер как rootfs-архив для последующего развертывания этого контейнера без повторной установки и настройки.
Вообще, идея Linux Deploy возникла из желания получить легкий и удобный инструмент для быстрого развертывания Linux-дистрибутива, который можно было бы использовать для целей разработки, тестирования или обучения, а затем быстро удалить его, не внося изменения в основную (хост) Linux-систему и не рискуя ее целостностью. Благодаря программе PRoot стало возможным создавать контейнеры для запуска Linux-приложений без прав суперпользователя (root), а также использовать программную эмуляцию QEMU для запуска приложений с отличающийся от хоста архитектурой без необходимости поддержки модуля binfmt_misc на уровне ядра.
Так вышло, что на моей основной работе с 2011 года используются компьютеры с Debian. Местные разработчики периодически нуждаются в системе для запуска и тестирования своих веб-приложений (в основном Java, PHP, Python). Для этих целей обычно использовались виртуальные системы либо на базе VirtualBox, либо в местном «облаке» Proxmox, либо Docker. Основным недостатком VirtualBox является его требовательность к ресурсам компьютера, большой размер VDI образа диска, относительно невысокая скорость работы и вероятность поломки образа VM при неправильном выключении системы. Недостатком при использовании «облака» можно назвать необходимость самому администратору обслуживать запросы пользователей на создание таких систем, а также расходование ресурсов «облака» на второстепенные задачи. Для работы с Docker требуются права суперпользователя.
В этом месяце был проведен эксперимент, PHP-разработчикам их виртуальный сервер был заменен на LD-контейнер. Были подготовлены два контейнера на базе Debian: Apache + PHP + OCI8 и Apache + PHP + MySQL + PhpMyAdmin. Контейнеры были размещены на общем сетевом диске в локальной сети, размер каждого контейнера составил около 150 МБ.
Что от этого получил администратор:
- один раз подготовленный контейнер может быть развернут на компьютере разработчика одной командой без участия администратора;
- работа с контейнером не требует прав суперпользователя, поэтому отсутствует риск поломки основной системы.
Что получил разработчик:
- развертывание, запуск и управление системой в контейнере осуществляется без участия администратора одной командой;
- развертывание контейнера из заранее подготовленных архивов осуществляется по сети менее чем за минуту;
- запуск и остановка контейнера (Веб-сервер + БД) происходит мгновенно, не нужно ждать запуска операционной системы;
- нет риска повредить контейнер, если забыл его отключить при выключении компьютера, т.к. образ системы представляет собой обычный каталог без собственной файловой системы;
- компьютер работает быстрее, т.к. ресурсы тратятся только на запускаемый софт в контейнере, а не на всю операционную систему (в нашем случае это порядка 50 МБ, вместо 500 МБ в VirtualBox).
- проверка работоспособности ПО прямо из каталога IDE без необходимости заливать его на сервер, для этого достаточно подключить к контейнеру необходимый каталог основной системы.
А теперь более подробно о том, как этого добиться. Далее будет приведена инструкция по подготовке и развертыванию LD-контейнера.
Для запуска контейнеров без прав суперпользователя необходимо установить PRoot:
Загрузка и установка Linux Deploy CLI:
Создание конфигурации с именем «linux» для развертывания базовой системы Debian Wheezy (64 бита):
Посмотреть сохраненную конфигурацию:
Запуск развертывания новой системы:
Подключение к консоли контейнера под пользователем root (для выхода команда exit):
Далее можно установить и настроить необходимый софт в контейнере, однако следует учитывать описанные ранее особенности. Например, для запуска Apache нужно поменять его порт (файл /etc/apache2/ports.conf) на 8000, установить пустой параметр APACHE_ULIMIT_MAX_FILES=» » (файл /etc/apache2/envvars), а сам apachectl запускать из-под обычного пользователя (не root).
Настройка автозапуска на базе системы инициализации SysV:
Параметры: INIT_LEVEL — уровень инициализации SysV, INIT_USER — из-под какого пользователя запускать сервисы (по умолчанию это root), INIT_ASYNC — запускать сервисы параллельно.
Подготовка конфигурации, экспорт ее и экспорт контейнера в rootfs-архив (поддерживаются tar.gz, tar.bz2 и tar.xz архивы):
Экранирование «\$» позволяет сохранять в конфиг имена переменных, а не их значения. Таким образом при импорте конфига эти переменные будут автоматически заменены на соответствующие значения, которые могут отличаться от текущих. Теперь есть два файла (linux.conf и linux.tgz), которые можно использовать при импорте контейнера на другом компьютере:
Подключить к контейнеру каталог основной системы (каталог
/www подключить в /var/www контейнера):
Запуск контейнера (для SysV выполняются сценарии /etc/rcN.d/SXXname start):
Остановка контейнера с освобождением ресурсов (для SysV выполняются сценарии /etc/rc6.d/KXXname stop):
В итоге получилось решение, которое удовлетворяет потребностям как разработчиков, так и администраторов. Исходные коды приложения Linux Deploy доступны под лицензией GPL версии 3.
Источник
Deploy linux images with
Copyright (C) 2012-2019 Anton Skshidlevsky, GPLv3
This application is open source software for quick and easy installation of the operating system (OS) GNU/Linux on your Android device.
The application creates a disk image or a directory on a flash card or uses a partition or RAM, mounts it and installs an OS distribution. Applications of the new system are run in a chroot environment and working together with the Android platform. All changes made on the device are reversible, i.e. the application and components can be removed completely. Installation of a distribution is done by downloading files from official mirrors online over the internet. The application can run better with superuser rights (root).
The program supports multi language interface. You can manage the process of installing the OS, and after installation, you can start and stop services of the new system (there is support for running your scripts) through the UI. The installation process is reported as text in the main application window. During the installation, the program will adjust the environment, which includes the base system, SSH server, VNC server and desktop environment. The program interface can also manage SSH and VNC settings.
Installing a new operating system takes about 15 minutes. The recommended minimum size of a disk image is 1024 MB (with LXDE), and without a GUI — 512 MB. When you install Linux on the flash card with the FAT32 file system, the image size should not exceed 4095 MB! After the initial setup the password for SSH and VNC generated automatically. The password can be changed through «Properties -> User password» or standard OS tools (passwd, vncpasswd).
The app is available for download in Google Play and GitHub.
- Bootstrap: Alpine, Arch, CentOS, Debian, Fedora, Kali, Slackware, Ubuntu, Docker or from rootfs.tar
- Installation type: image file, directory, disk partition, RAM
- Supported file systems: ext2, ext3, ext4
- Supported architectures: arm, arm64, x86, x86_64, emulation mode (ARM
x86)
Do not work update operating environment or errors appear in debug mode: «Permission denied», «Socket operation on non-socket» or other.
Install compatible BusyBox in /system/xbin, add path /system/xbin in «Settings -> PATH variable», update the operating environment «Settings -> Update ENV». Before upgrading the environment, it is desirable restart the device. After that, the container options must be selected «Properties -> File system -> Auto» and «Propetries -> Image size (MB) -> 2000», because «busybox mke2fs» is not supperted an option «-t» to specify type of file system and not supperted image greater 2 GB. Now you can start a new installation «Menu -> Install».
Making an image on sdcard return an error «Read-only file system».
If you are using SuperSU utility you need to uncheck «mount namespace separation» in SuperSU settings. See documentation.
Installing an application on Google Play fails with the message «Unknown error code during application installation: -24».
You need to remove the application directory: /data/data/ru.meefik.linuxdeploy
SD card read / write speed (10 class) on Android (Samsung Galaxy S II) for file systems vfat, ext2, ext4:
- vfat: read speed 14.1 MB/s; write speed 12.0 MB/s
- ext2: read speed 14.9 MB/s; write speed 3.9 MB/s
- ext4: read speed 14.9 MB/s; write speed 16.6 MB/s
- ext2 (loop): read speed 17.0 MB/s; write speed 7.4 MB/s
- ext4 (loop): read speed 17.2 MB/s; write speed 8.8 MB/s
Installation time and use space on disk (Debian wheezy/armhf on Samsung Galaxy S II):
Источник
Deploy linux images with
linuxdeployqt
This Linux Deployment Tool, linuxdeployqt , takes an application as input and makes it self-contained by copying in the resources that the application uses (like libraries, graphics, and plugins) into a bundle. The resulting bundle can be distributed as an AppDir or as an AppImage to users, or can be put into cross-distribution packages. It can be used as part of the build process to deploy applications written in C, C++, and other compiled languages with systems like CMake , qmake , and make . When used on Qt-based applications, it can bundle a specific minimal subset of Qt required to run the application.
Differences to macdeployqt
This tool is conceptually based on the Mac Deployment Tool, macdeployqt in the tools applications of the Qt Toolkit, but has been changed to a slightly different logic and other tools needed for Linux.
- Instead of an .app bundle for macOS, this produces an AppDir for Linux
- Instead of a .dmg disk image for macOS, this produces an AppImage for Linux which is quite similar to a dmg but executes the contained application rather than just opening a window on the desktop from where the application can be launched
A note on binary compatibility
To produce binaries that are compatible with many target systems, build on the oldest still-supported build system. The oldest still-supported release of Ubuntu is currently targeted, tested and supported by the team.
We recommend to target the oldest still-supported Ubuntu LTS release and build your applications on that. If you do this, the resulting binaries should be able to run on newer (but not older) systems (Ubuntu and other distributions).
We do not support linuxdeployqt on systems newer than the oldest Ubuntu LTS release, because we want to encourage developers to build applications in a way that makes them possible to run on all still-supported distribution releases. For an overview about the support cycles of Ubuntu LTS releases, please see https://wiki.ubuntu.com/Releases.
Please download linuxdeployqt-x86_64.AppImage from the Releases page and chmod a+x it. If you would like to build linuxdeployqt from source instead, see BUILDING.md.
: Let the given executable use the deployed libraries too -extra-plugins=
: List of extra plugins which should be deployed, separated by comma. -no-copy-copyright-files : Skip deployment of copyright files. -no-plugins : Skip plugin deployment. -no-strip : Don’t run ‘strip’ on the binaries. -no-translations : Skip deployment of translations. -qmake=
: The qmake executable to use. -qmldir=
: Scan for QML imports in the given path. -qmlimport=
: Add the given path to QML module search locations. -show-exclude-libs : Print exclude libraries list. -verbose= : 0 = no output, 1 = error/warning (default), 2 = normal, 3 = debug. -updateinformation= : Embed update information STRING; if zsyncmake is installed, generate zsync file -version : Print version statement and exit. linuxdeployqt takes an application as input and makes it self-contained by copying in the Qt libraries and plugins that the application uses. By default it deploys the Qt instance that qmake on the $PATH points to. The ‘-qmake’ option can be used to point to the qmake executable to be used instead. Plugins related to a Qt library are copied in with the library. See the «Deploying Applications on Linux» topic in the documentation for more information about deployment on Linux. «>
You’ll need to provide the basic structure of an AppDir which should look something like this:
Replace
Using the desktop file linuxdeployqt can determine the parameters of the build.
Where your desktop file would look something like:
- Notice that both Exec and Icon only have file names.
- Also Notice that the Icon entry does not include an extension.
Read more about desktop files in the Desktop Entry Specification 1.0.
Now you can say: linuxdeployqt-continuous-x86_64.AppImage path/to/AppDir/usr/share/applications/your_app.desktop
For a more detailed example, see «Using linuxdeployqt with Travis CI» below.
Checking library inclusion
Open in Qt Creator and build your application. Run it from the command line and inspect it with ldd to make sure the correct libraries from the correct locations are getting loaded, as linuxdeployqt will use ldd internally to determine from where to copy libraries into the bundle.
Important: By default, linuxdeployqt deploys the Qt instance that qmake on the $PATH points to, so make sure that it is the correct one. Verify that qmake finds the correct Qt instance like this before running the linuxdeployqt tool:
If this does not show the correct path to your Qt instance that you want to be bundled, then adjust your $PATH to find the correct qmake .
Alternatively, use the -qmake command line option to point the tool directly to the qmake executable to be used.
Remove unnecessary files
Before running linuxdeployqt it may be wise to delete unneeded files that you do not wish to distribute from the build directory. These may be autogenerated during the build. You can delete them like so:
Alternatively, you could use $DESTDIR .
Adding icon and icon theme support
To enable icon and icon theme support you must add iconengines as an extra Qt plugin while running linuxdeployqt . In order for your application to locate the system theme icons, the libqgtk3.so platform theme must also be added:
Adding extra Qt plugins
If you want aditional plugins which the tool doesn’t deploy, for a variety of reasons, you can use the -extra-plugins argument and include a list of plugins separated by a comma.
The plugins deployed are from the Qt installation pointed out by qmake -v .
You can deploy entire plugin directories, a specific directory or a mix of both.
- -extra-plugins=sqldrivers/libqmsql.so,iconengines/libqsvgicon.so
- -extra-plugins=sqldrivers,iconengines/libqsvgicon.so
- -extra-plugins=sqldrivers,iconengines,mediaservice,gamepads
Handle Qt libraries infix
If you prepared a custom Qt distribution using the option -qtlibinfix during Qt configuration (resulting in library names such as libQt5CoreCustom.so ), you must mention this infix on linuxdeployqt call. As an example, let’s see if we configure our distribution using the infix Custom .
On Qt build chain: configure -qtlibinfix «Custom» [. ] . This will generate Qt libraries (.so) like libQt5CoreCustom.so
So, on linuxdeployqt call: linuxdeployqt [. ] -qtlibinfix «Custom» [. ] .
If you don’t mention this infix, linuxdeployqt won’t be able to detect Qt Core and Widgets libraries.
Using linuxdeployqt with Travis CI
A common use case for linuxdeployqt is to use it on Travis CI after the make command. The following example illustrates how to use linuxdeployqt with Travis CI. Create a .travis.yml file similar to this one (be sure to customize it, e.g., change APPNAME to the name of your application as it is spelled in the Name= entry of the .desktop file):
When you save your change, then Travis CI should build and upload an AppImage for you. More likely than not, some fine-tuning will still be required.
For this to work, you need to set up GITHUB_TOKEN in Travis CI; please see https://github.com/probonopd/uploadtool.
By default, qmake .pro files generated by Qt Creator unfortunately don’t support make install out of the box. In this case you will get
Fix for «make: Nothing to be done for ‘install'»
If qmake does not allow for make install or does not install the desktop file and icon, then you need to change your .pro file it similar to https://github.com/probonopd/FeedTheMonkey/blob/master/FeedTheMonkey.pro.
Here is another simple example.
It is common on Unix to also use the build tool to install applications and libraries; for example, by invoking make install . For this reason, qmake has the concept of an install set, an object which contains instructions about the way a part of a project is to be installed.
For projects that use CMake, autotools, or meson with ninja instead of qmake
CMake wants DESTDIR instead:
Some applications have the bad habit of relying on CMake versions newer than what comes with the oldest still-supported distributions. In this case, install a newer CMake with
Under some circumstances it may also be required to add -DCMAKE_INSTALL_LIBDIR=/usr/lib to the cmake call.
autotools (the dinosaur that spends precious minutes «checking. «) wants DESTDIR too but insists on an absolute link which we can feed it using readlink:
Caution if you encounter
Here, CONFIG+=use_qt_paths needs to be removed, otherwise it will install everything under the Qt installation paths in /opt/qt58 when using the beineri ppa.
The exception is that you are building Qt libraries that should be installed to the same location where Qt resides on your system, from where it will be picked up by linuxdeployqt .
meson with ninja apparently wants
When using Qt from distribution packages
On Ubuntu 14.04, you will need to pass in -qmake=/usr/lib/x86_64-linux-gnu/qt5/bin/qmake when using distribution packages.
A note on DESTDIR
Automating DESTDIR can be a pain, so it’s best if the program supports it to start with; my package Auto-DESTDIR can automatically support DESTDIR in some cases if the program installation does not support it to begin with.
Sending Pull Requests on GitHub
linuxdeployqt is great for upstream application projects that want to release their software in binary form to Linux users quickly and without much overhead. If you would like to see a particular application use linuxdeployqt , then sending a Pull Request may be an option to get the upstream application project to consider it. You can use the following template text for Pull Requests but make sure to customize it to the project in question.
Projects using linuxdeployqt
These projects are already using Travis CI and linuxdeployqt to provide AppImages of their builds:
These projects are using GitHub Actions and linuxdeployqt to provide AppImages of their builds:
This project is already using linuxdeployqt in a custom Jenkins workflow:
This GitHub template invokes linuxdeployqt during a GitHub CI Action:
These projects are already using linuxdeployqt:
This project on GitLab uses linuxdeployqt:
This project can be bundled successfully using linuxdeployqt:
One great way to contribute is to send Pull Requests to the application projects you’d like to see use linuxdeployqt, as described above. You are also welcome to contribute to linuxdeployqt development itself. Please discuss in the forum or using GitHub issues and Pull Requests.
The developers are in the channel #AppImage on irc.freenode.net
About
Makes Linux applications self-contained by copying in the libraries and plugins that the application uses, and optionally generates an AppImage. Can be used for Qt and other applications
Источник