Merge pull request #187 from Jip-Hop/develop

v2.0.0
This commit is contained in:
Jip-Hop 2024-05-28 20:59:51 +02:00 committed by GitHub
commit 955d80f31d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 349 additions and 402 deletions

165
LICENSE Normal file
View File

@ -0,0 +1,165 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.

288
README.md
View File

@ -21,9 +21,152 @@ TrueNAS SCALE can create persistent Linux 'jails' with systemd-nspawn. This scri
- Optional: GPU passthrough (including nvidia GPU with the drivers bind mounted from the host) - Optional: GPU passthrough (including nvidia GPU with the drivers bind mounted from the host)
- Starting the jail with your config applied - Starting the jail with your config applied
## Installation
Beginning with 24.04 (Dragonfish), TrueNAS SCALE officially includes the systemd-nspawn containerization program in the base system. Technically there's nothing to install. You only need the `jlmkr.py` script file in the right place. [Instructions with screenshots](https://www.truenas.com/docs/scale/scaletutorials/apps/sandboxes/) are provided on the TrueNAS website. Start by creating a new dataset called `jailmaker` with the default settings (from TrueNAS web interface). Then login as the root user and download `jlmkr.py`.
```shell
cd /mnt/mypool/jailmaker
curl --location --remote-name https://raw.githubusercontent.com/Jip-Hop/jailmaker/main/jlmkr.py
chmod +x jlmkr.py
```
The `jlmkr.py` script (and the jails + config it creates) are now stored on the `jailmaker` dataset and will survive updates of TrueNAS SCALE. If the automatically created `jails` directory is also a ZFS dataset (which is true for new users), then the `jlmkr.py` script will automatically create a new dataset for every jail created. This allows you to snapshot individual jails. For legacy users (where the `jails` directory is not a dataset) each jail will be stored in a plain directory.
### Alias
Optionally you may create a shell alias for the currently logged in (admin) user to conveniently run `jlmkr.py` without having to change into the `jailmaker` directory or specify the full absolute path. I suggest to create the `jlmkr` alias like this:
```shell
echo "alias jlmkr=\"sudo '/mnt/mypool/jailmaker/jlmkr.py'\"" > ~/.bashrc
```
Please replace `/mnt/mypool/jailmaker/` with the actual path to where you stored `jlmkr.py`. If you're using zsh instead of bash, then you should replace `.bashrc` in the command above with `.zshrc`. If you've created the alias, you may use it instead of `./jlmkr.py`.
## Usage
### Create Jail
Creating a jail with the default settings is as simple as:
```shell
./jlmkr.py create --start myjail
```
You may also specify a path to a config template, for a quick and consistent jail creation process.
```shell
./jlmkr.py create --start --config /path/to/config/template myjail
```
Or you can override the default config by using flags. See `./jlmkr.py create --help` for the available options. Anything passed after the jail name will be passed to `systemd-nspawn` when starting the jail. See the `systemd-nspawn` manual for available options, specifically [Mount Options](https://manpages.debian.org/bookworm/systemd-container/systemd-nspawn.1.en.html#Mount_Options) and [Networking Options](https://manpages.debian.org/bookworm/systemd-container/systemd-nspawn.1.en.html#Networking_Options) are frequently used.
```shell
./jlmkr.py create --start --distro=ubuntu --release=jammy myjail --bind-ro=/mnt
```
If you omit the jail name, the create process is interactive. You'll be presented with questions which guide you through the process.
```shell
./jlmkr.py create
```
After answering some questions you should have created your first jail (and it should be running if you chose to start it after creating)!
### Startup Jails on Boot
```shell
# Call startup using the absolute path to jlmkr.py
/mnt/mypool/jailmaker/jlmkr.py startup
```
In order to start jails automatically after TrueNAS boots, run `/mnt/mypool/jailmaker/jlmkr.py startup` as Post Init Script with Type `Command` from the TrueNAS web interface. This will start all the jails with `startup=1` in the config file.
### Start Jail
```shell
./jlmkr.py start myjail
```
### List Jails
See list of jails (including running, startup state, GPU passthrough, distro, and IP).
```shell
./jlmkr.py list
```
### Execute Command in Jail
You may want to execute a command inside a jail, for example manually from the TrueNAS shell, a shell script or a CRON job. The example below executes the `env` command inside the jail.
```shell
./jlmkr.py exec myjail env
```
This example executes bash inside the jail with a command as additional argument.
```shell
./jlmkr.py exec myjail bash -c 'echo test; echo $RANDOM;'
```
### Edit Jail Config
```shell
./jlmkr.py edit myjail
```
Once you've created a jail, it will exist in a directory inside the `jails` dir next to `jlmkr.py`. For example `/mnt/mypool/jailmaker/jails/myjail` if you've named your jail `myjail`. You may edit the jail configuration file using the `./jlmkr.py edit myjail` command. This opens the config file in your favorite editor, as determined by following [Debian's guidelines](https://www.debian.org/doc/debian-policy/ch-customized-programs.html#editors-and-pagers) on the matter. You'll have to stop the jail and start it again with `jlmkr` for these changes to take effect.
### Remove Jail
Delete a jail and remove it's files (requires confirmation).
```shell
./jlmkr.py remove myjail
```
### Stop Jail
```shell
./jlmkr.py stop myjail
```
### Restart Jail
```shell
./jlmkr.py restart myjail
```
### Jail Shell
Switch into the jail's shell.
```shell
./jlmkr.py shell myjail
```
### Jail Status
```shell
./jlmkr.py status myjail
```
### Jail Logs
View a jail's logs.
```shell
./jlmkr.py log myjail
```
### Additional Commands
Expert users may use the following additional commands to manage jails directly: `machinectl`, `systemd-nspawn`, `systemd-run`, `systemctl` and `journalctl`. The `jlmkr` script uses these commands under the hood and implements a subset of their functions. If you use them directly you will bypass any safety checks or configuration done by `jlmkr` and not everything will work in the context of TrueNAS SCALE.
## Security ## Security
Despite what the word 'jail' implies, jailmaker's intended use case is to create one or more additional filesystems to run alongside SCALE with minimal isolation. By default the root user in the jail with uid 0 is mapped to the host's uid 0. This has [obvious security implications](https://linuxcontainers.org/lxc/security/#privileged-containers). If this is not acceptable to you, you may lock down the jails by [limiting capabilities](https://manpages.debian.org/bookworm/systemd-container/systemd-nspawn.1.en.html#Security_Options) and/or using [user namespacing](https://manpages.debian.org/bookworm/systemd-container/systemd-nspawn.1.en.html#User_Namespacing_Options) or use a VM instead. By default the root user in the jail with uid 0 is mapped to the host's uid 0. This has [obvious security implications](https://linuxcontainers.org/lxc/security/#privileged-containers). If this is not acceptable to you, you may lock down the jails by [limiting capabilities](https://manpages.debian.org/bookworm/systemd-container/systemd-nspawn.1.en.html#Security_Options) and/or using [user namespacing](https://manpages.debian.org/bookworm/systemd-container/systemd-nspawn.1.en.html#User_Namespacing_Options) or use a VM instead.
### Seccomp ### Seccomp
Seccomp is a Linux kernel feature that restricts programs from making unauthorized system calls. This means that when seccomp is enabled there can be times where a process run inside a jail will be killed with the error "Operation not permitted." In order to find out which syscall needs to be added to the `--system-call-filter=` configuration you can use `strace`. Seccomp is a Linux kernel feature that restricts programs from making unauthorized system calls. This means that when seccomp is enabled there can be times where a process run inside a jail will be killed with the error "Operation not permitted." In order to find out which syscall needs to be added to the `--system-call-filter=` configuration you can use `strace`.
@ -37,149 +180,10 @@ Failed to initialize PMU! (Operation not permitted)
perf_event_open({type=0x10 /* PERF_TYPE_??? */, size=PERF_ATTR_SIZE_VER7, config=0x100002, sample_period=0, sample_type=0, read_format=PERF_FORMAT_TOTAL_TIME_ENABLED|PERF_FORMAT_GROUP, precise_ip=0 /* arbitrary skid */, use_clockid=1, ...}, -1, 0, -1, 0) = -1 EPERM (Operation not permitted) perf_event_open({type=0x10 /* PERF_TYPE_??? */, size=PERF_ATTR_SIZE_VER7, config=0x100002, sample_period=0, sample_type=0, read_format=PERF_FORMAT_TOTAL_TIME_ENABLED|PERF_FORMAT_GROUP, precise_ip=0 /* arbitrary skid */, use_clockid=1, ...}, -1, 0, -1, 0) = -1 EPERM (Operation not permitted)
write(2, "Failed to initialize PMU! (Opera"..., 52Failed to initialize PMU! (Operation not permitted) write(2, "Failed to initialize PMU! (Opera"..., 52Failed to initialize PMU! (Operation not permitted)
``` ```
The syscall that needs to be added to the `--system-call-filter` option in the jlmkr config in this case would be `perf_event_open`. You may need to run strace multiple times. The syscall that needs to be added to the `--system-call-filter` option in the `jailmaker` config in this case would be `perf_event_open`. You may need to run strace multiple times.
Seccomp is important for security, but as a last resort can be disabled by setting `seccomp=0` in the jail config. Seccomp is important for security, but as a last resort can be disabled by setting `seccomp=0` in the jail config.
## Installation
Beginning with 24.04 (Dragonfish), TrueNAS SCALE includes the systemd-nspawn containerization program in the base system. Technically there's nothing to install. You only need the `jlmkr.py` script file in the right place. [Instructions with screenshots](https://www.truenas.com/docs/scale/scaletutorials/apps/sandboxes/) are provided on the TrueNAS website. Start by creating a new dataset called `jailmaker` with the default settings (from TrueNAS web interface). Then login as the root user and download `jlmkr.py`. If you login as non-root user (e.g. as admin), **you must become root first** by executing `sudo su`.
```shell
cd /mnt/mypool/jailmaker
curl --location --remote-name https://raw.githubusercontent.com/Jip-Hop/jailmaker/main/jlmkr.py
chmod +x jlmkr.py
./jlmkr.py install
```
The `jlmkr.py` script (and the jails + config it creates) are now stored on the `jailmaker` dataset and will survive updates of TrueNAS SCALE. If the automatically created `jails` directory is also a ZFS dataset (which is true for new users), then the `jlmkr.py` script will automatically create a new dataset for every jail created. This allows you to snapshot individual jails. For legacy users (where the `jails` directory is not a dataset) each jail will be stored in a plain directory.
A symlink has been created so you can call `jlmkr` from anywhere (unless the boot pool is readonly, which is the default since SCALE 24.04). Additionally shell aliases have been setup, so you can still call `jlmkr` in an interactive shell (even if the symlink couldn't be created).
After an update of TrueNAS SCALE the symlink will be lost (but the shell aliases will remain). To restore the symlink, just run `./jlmkr.py install` again or use [the `./jlmkr.py startup` command](#startup-jails-on-boot).
## Usage
### Create Jail
Creating jail with the default settings is as simple as:
```shell
jlmkr create --start myjail
```
You may also specify a path to a config template, for a quick and consistent jail creation process.
```shell
jlmkr create --start --config /path/to/config/template myjail
```
Or you can override the default config by using flags. See `jlmkr create --help` for the available options. Anything passed after the jail name will be passed to `systemd-nspawn` when starting the jail. See the `systemd-nspawn` manual for available options, specifically [Mount Options](https://manpages.debian.org/bookworm/systemd-container/systemd-nspawn.1.en.html#Mount_Options) and [Networking Options](https://manpages.debian.org/bookworm/systemd-container/systemd-nspawn.1.en.html#Networking_Options) are frequently used.
```shell
jlmkr create --start --distro=ubuntu --release=jammy myjail --bind-ro=/mnt
```
If you omit the jail name, the create process is interactive. You'll be presented with questions which guide you through the process.
```shell
jlmkr create
```
After answering some questions you should have created your first jail (and it should be running if you chose to start it after creating)!
### Startup Jails on Boot
```shell
# Call startup using the absolute path to jlmkr.py
# The jlmkr shell alias doesn't work in Init/Shutdown Scripts
/mnt/mypool/jailmaker/jlmkr.py startup
```
In order to start jails automatically after TrueNAS boots, run `/mnt/mypool/jailmaker/jlmkr.py startup` as Post Init Script with Type `Command` from the TrueNAS web interface. This creates the `jlmkr` symlink (if possible), as well as start all the jails with `startup=1` in the config file.
### Start Jail
```shell
jlmkr start myjail
```
### List Jails
See list of jails (including running, startup state, GPU passthrough, distro, and IP).
```shell
jlmkr list
```
### Execute Command in Jail
You may want to execute a command inside a jail, for example manually from the TrueNAS shell, a shell script or a CRON job. The example below executes the `env` command inside the jail.
```shell
jlmkr exec myjail env
```
This example executes bash inside the jail with a command as additional argument.
```shell
jlmkr exec myjail bash -c 'echo test; echo $RANDOM;'
```
### Edit Jail Config
```shell
jlmkr edit myjail
```
Once you've created a jail, it will exist in a directory inside the `jails` dir next to `jlmkr.py`. For example `/mnt/mypool/jailmaker/jails/myjail` if you've named your jail `myjail`. You may edit the jail configuration file using the `jlmkr edit myjail` command. This opens the config file in your favorite editor, as determined by following [Debian's guidelines](https://www.debian.org/doc/debian-policy/ch-customized-programs.html#editors-and-pagers) on the matter. You'll have to stop the jail and start it again with `jlmkr` for these changes to take effect.
### Remove Jail
Delete a jail and remove it's files (requires confirmation).
```shell
jlmkr remove myjail
```
### Stop Jail
```shell
jlmkr stop myjail
```
### Restart Jail
```shell
jlmkr restart myjail
```
### Jail Shell
Switch into the jail's shell.
```shell
jlmkr shell myjail
```
### Jail Status
```shell
jlmkr status myjail
```
### Jail Logs
View a jail's logs.
```shell
jlmkr log myjail
```
### Additional Commands
Expert users may use the following additional commands to manage jails directly: `machinectl`, `systemd-nspawn`, `systemd-run`, `systemctl` and `journalctl`. The `jlmkr` script uses these commands under the hood and implements a subset of their functions. If you use them directly you will bypass any safety checks or configuration done by `jlmkr` and not everything will work in the context of TrueNAS SCALE.
## Networking ## Networking
By default a jails will use the same networking namespace, with access to all (physical) interfaces the TrueNAS host has access to. No further setup is required. You may download and install additional packages inside the jail. Note that some ports are already occupied by TrueNAS SCALE (e.g. 443 for the web interface), so your jail can't listen on these ports. By default a jails will use the same networking namespace, with access to all (physical) interfaces the TrueNAS host has access to. No further setup is required. You may download and install additional packages inside the jail. Note that some ports are already occupied by TrueNAS SCALE (e.g. 443 for the web interface), so your jail can't listen on these ports.
@ -208,7 +212,7 @@ The rootfs image `jlmkr.py` downloads comes from the [Linux Containers Image ser
## Filing Issues and Community Support ## Filing Issues and Community Support
When in need of help or when you think you've found a bug in jailmaker, [please start with reading this](https://github.com/Jip-Hop/jailmaker/discussions/135). When in need of help or when you think you've found a bug in `jailmaker`, [please start with reading this](https://github.com/Jip-Hop/jailmaker/discussions/135).
## References ## References

View File

@ -52,7 +52,7 @@ See [Networking](./network.md)
### Colorized bash prompt ### Colorized bash prompt
To visually distinguish between a root shell inside the jail and a root shell outside the jail, it's possible to colorize the shell prompt. When using a debian jail with the bash shell, you may run the following command **inside the jail** to get a yellow prompt inside the jail (will be activated the next time you run `jlmkr shell myjail`): To visually distinguish between a root shell inside the jail and a root shell outside the jail, it's possible to colorize the shell prompt. When using a debian jail with the bash shell, you may run the following command **inside the jail** to get a yellow prompt inside the jail (will be activated the next time you run `./jlmkr.py shell myjail`):
```bash ```bash
echo "PS1='${debian_chroot:+($debian_chroot)}\[\033[01;33m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '" >> ~/.bashrc echo "PS1='${debian_chroot:+($debian_chroot)}\[\033[01;33m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '" >> ~/.bashrc

View File

@ -4,7 +4,7 @@
| | | | | |
|---|---| |---|---|
|TrueNAS Core|❌| |TrueNAS Core|❌|
|TrueNAS 22.12|| |TrueNAS 22.12||
|TrueNAS 23.10|✅| |TrueNAS 23.10|✅|
|TrueNAS 24.04|✅| |TrueNAS 24.04|✅|

View File

@ -91,7 +91,7 @@ DHCP=false
Address=192.168.X.XXX/24 Address=192.168.X.XXX/24
Gateway=192.168.X.X Gateway=192.168.X.X
``` ```
Then restart the network interface inside the jail `systemctl restart systemd-networkd` or restart the jail by running `jlmkr stop JAILNAME && jlmkr start JAILNAME` from the TrueNAS shell. Use `ifconfig` to verify the interface is up and has the correct IP. Then restart the network interface inside the jail `systemctl restart systemd-networkd` or restart the jail by running `./jlmkr.py stop JAILNAME && ./jlmkr.py start JAILNAME` from the TrueNAS shell. Use `ifconfig` to verify the interface is up and has the correct IP.
## DNS via DHCP ## DNS via DHCP

View File

@ -11,9 +11,9 @@ Jailmaker operates in dual-mode: it supports using both directories and datasets
#### Stop all jails #### Stop all jails
`jlmkr stop jail1` `./jlmkr.py stop jail1`
`jlmkr stop jail2` `./jlmkr.py stop jail2`
etc.. etc..
#### Move/rename the 'jailmaker' directory #### Move/rename the 'jailmaker' directory
@ -56,6 +56,6 @@ Warning! It's important that both directories have the `/` at the end to make su
#### Test everything works #### Test everything works
If everything works, you should be able to use the `jlmkr` command directly. Try doing a `jlmkr list` to check if the jails are correctly recognized If everything works, you should be able to use the `./jlmkr.py` command directly. Try doing a `./jlmkr.py list` to check if the jails are correctly recognized
You can also try creating a new jail and see that the dataset is created automatically. You can also try creating a new jail and see that the dataset is created automatically.

258
jlmkr.py
View File

@ -4,17 +4,16 @@
with full access to all files via bind mounts, \ with full access to all files via bind mounts, \
thanks to systemd-nspawn!""" thanks to systemd-nspawn!"""
__version__ = "1.5.0" __version__ = "2.0.0"
__author__ = "Jip-Hop" __author__ = "Jip-Hop"
__copyright__ = "Copyright (C) 2023, Jip-Hop"
__license__ = "LGPL-3.0-only"
__disclaimer__ = """USE THIS SCRIPT AT YOUR OWN RISK! __disclaimer__ = """USE THIS SCRIPT AT YOUR OWN RISK!
IT COMES WITHOUT WARRANTY AND IS NOT SUPPORTED BY IXSYSTEMS.""" IT COMES WITHOUT WARRANTY AND IS NOT SUPPORTED BY IXSYSTEMS."""
import argparse import argparse
import configparser import configparser
import contextlib import contextlib
import ctypes
import errno
import glob
import hashlib import hashlib
import io import io
import json import json
@ -38,8 +37,6 @@ from textwrap import dedent
DEFAULT_CONFIG = """startup=0 DEFAULT_CONFIG = """startup=0
gpu_passthrough_intel=0 gpu_passthrough_intel=0
gpu_passthrough_nvidia=0 gpu_passthrough_nvidia=0
# The docker_compatible option is deprecated and will be removed in a future release
docker_compatible=0
# Turning off seccomp filtering improves performance at the expense of security # Turning off seccomp filtering improves performance at the expense of security
seccomp=1 seccomp=1
@ -128,7 +125,7 @@ SCRIPT_PATH = os.path.realpath(__file__)
SCRIPT_NAME = os.path.basename(SCRIPT_PATH) SCRIPT_NAME = os.path.basename(SCRIPT_PATH)
SCRIPT_DIR_PATH = os.path.dirname(SCRIPT_PATH) SCRIPT_DIR_PATH = os.path.dirname(SCRIPT_PATH)
COMMAND_NAME = os.path.basename(__file__) COMMAND_NAME = os.path.basename(__file__)
SYMLINK_NAME = "jlmkr" SHORTNAME = "jlmkr"
# Only set a color if we have an interactive tty # Only set a color if we have an interactive tty
if sys.stdout.isatty(): if sys.stdout.isatty():
@ -337,7 +334,7 @@ def passthrough_nvidia(
): ):
jail_rootfs_path = get_jail_rootfs_path(jail_name) jail_rootfs_path = get_jail_rootfs_path(jail_name)
ld_so_conf_path = Path( ld_so_conf_path = Path(
os.path.join(jail_rootfs_path), f"etc/ld.so.conf.d/{SYMLINK_NAME}-nvidia.conf" os.path.join(jail_rootfs_path), f"etc/ld.so.conf.d/{SHORTNAME}-nvidia.conf"
) )
if not gpu_passthrough_nvidia: if not gpu_passthrough_nvidia:
@ -480,7 +477,7 @@ def status_jail(jail_name):
""" """
# Alternatively `machinectl status jail_name` could be used # Alternatively `machinectl status jail_name` could be used
return subprocess.run( return subprocess.run(
["systemctl", "status", f"{SYMLINK_NAME}-{jail_name}"] ["systemctl", "status", f"{SHORTNAME}-{jail_name}"]
).returncode ).returncode
@ -489,7 +486,7 @@ def log_jail(jail_name):
Show the log file of the jail with given name. Show the log file of the jail with given name.
""" """
return subprocess.run( return subprocess.run(
["journalctl", "-u", f"{SYMLINK_NAME}-{jail_name}"] ["journalctl", "-u", f"{SHORTNAME}-{jail_name}"]
).returncode ).returncode
@ -574,7 +571,7 @@ def start_jail(jail_name):
seccomp = config.my_getboolean("seccomp") seccomp = config.my_getboolean("seccomp")
systemd_run_additional_args = [ systemd_run_additional_args = [
f"--unit={SYMLINK_NAME}-{jail_name}", f"--unit={SHORTNAME}-{jail_name}",
f"--working-directory=./{jail_path}", f"--working-directory=./{jail_path}",
f"--description=My nspawn jail {jail_name} [created with jailmaker]", f"--description=My nspawn jail {jail_name} [created with jailmaker]",
] ]
@ -602,47 +599,6 @@ def start_jail(jail_name):
# Or pull docker images containing device nodes: # Or pull docker images containing device nodes:
# docker pull oraclelinux@sha256:d49469769e4701925d5145c2676d5a10c38c213802cf13270ec3a12c9c84d643 # docker pull oraclelinux@sha256:d49469769e4701925d5145c2676d5a10c38c213802cf13270ec3a12c9c84d643
if config.my_getboolean("docker_compatible"):
eprint("WARNING: DEPRECATED OPTION")
eprint(
"The `docker_compatible` option is deprecated and will be removed in a future release."
)
eprint("Please refer to the recommended way to run docker in a jail:")
eprint("https://github.com/Jip-Hop/jailmaker/tree/main/templates/docker")
# Enable ip forwarding on the host (docker needs it)
print(1, file=open("/proc/sys/net/ipv4/ip_forward", "w"))
# Load br_netfilter kernel module and enable bridge-nf-call to fix warning when running docker info:
# WARNING: bridge-nf-call-iptables is disabled
# WARNING: bridge-nf-call-ip6tables is disabled
#
# If we are using Apps then this should already be enabled
# May cause "guest container traffic to be blocked by iptables rules that are intended for the host"
# https://unix.stackexchange.com/q/720105/477308
# https://github.com/moby/moby/issues/24809
# https://docs.oracle.com/en/operating-systems/oracle-linux/docker/docker-KnownIssues.html#docker-issues
# https://wiki.libvirt.org/page/Net.bridge.bridge-nf-call_and_sysctl.conf
# https://serverfault.com/questions/963759/docker-breaks-libvirt-bridge-network
if subprocess.run(["modprobe", "br_netfilter"]).returncode == 0:
print(1, file=open("/proc/sys/net/bridge/bridge-nf-call-iptables", "w"))
print(1, file=open("/proc/sys/net/bridge/bridge-nf-call-ip6tables", "w"))
else:
eprint(
dedent(
"""
Failed to load br_netfilter kernel module."""
)
)
print("The `docker_compatible` option disables seccomp filtering...")
seccomp = False
# Add additional flags required for docker
systemd_nspawn_additional_args += [
"--capability=all",
]
# Add hooks to execute commands on the host before/after starting and after stopping a jail # Add hooks to execute commands on the host before/after starting and after stopping a jail
add_hook( add_hook(
jail_path, jail_path,
@ -665,20 +621,8 @@ def start_jail(jail_name):
"ExecStopPost", "ExecStopPost",
) )
# Legacy gpu_passthrough config setting gpu_passthrough_intel = config.my_getboolean("gpu_passthrough_intel")
if config.my_getboolean("gpu_passthrough", False): gpu_passthrough_nvidia = config.my_getboolean("gpu_passthrough_nvidia")
eprint("WARNING: DEPRECATED OPTION")
eprint(
"The `gpu_passthrough` option is deprecated and will be removed in a future release."
)
eprint(
"Please use `gpu_passthrough_intel` and/or `gpu_passthrough_nvidia` instead."
)
gpu_passthrough_intel = True
gpu_passthrough_nvidia = True
else:
gpu_passthrough_intel = config.my_getboolean("gpu_passthrough_intel")
gpu_passthrough_nvidia = config.my_getboolean("gpu_passthrough_nvidia")
passthrough_intel(gpu_passthrough_intel, systemd_nspawn_additional_args) passthrough_intel(gpu_passthrough_intel, systemd_nspawn_additional_args)
passthrough_nvidia( passthrough_nvidia(
@ -759,7 +703,7 @@ def start_jail(jail_name):
f""" f"""
Failed to start jail {jail_name}... Failed to start jail {jail_name}...
In case of a config error, you may fix it with: In case of a config error, you may fix it with:
{SYMLINK_NAME} edit {jail_name} {COMMAND_NAME} edit {jail_name}
""" """
) )
) )
@ -1223,37 +1167,15 @@ def interactive_config():
) )
) )
# Enable tab auto completion of file paths after the = symbol
readline.set_completer_delims("=")
readline.parse_and_bind("tab: complete")
readline_lib = ctypes.CDLL(readline.__file__)
rl_completer_quote_characters = ctypes.c_char_p.in_dll(
readline_lib, "rl_completer_quote_characters"
)
# Let the readline library know about quote characters for completion
rl_completer_quote_characters.value = "\"'".encode("utf-8")
# TODO: more robust tab completion of file paths with space or = character
# Currently completing these only works when the path is quoted
# https://thoughtbot.com/blog/tab-completion-in-gnu-readline
# https://stackoverflow.com/a/67118744
# https://github.com/python-cmd2/cmd2/blob/ee7599f9ac0dbb6ce3793f6b665ba1200d3ef9a3/cmd2/cmd2.py
# https://stackoverflow.com/a/40152927
config.my_set( config.my_set(
"systemd_nspawn_user_args", "systemd_nspawn_user_args",
"\n ".join(shlex.split(input("Additional flags: ") or "")), "\n ".join(shlex.split(input("Additional flags: ") or "")),
) )
# Disable tab auto completion
readline.parse_and_bind("tab: self-insert")
print( print(
dedent( dedent(
f""" f"""
The `{COMMAND_NAME} startup` command can automatically ensure {COMMAND_NAME} is installed properly and start a selection of jails. The `{COMMAND_NAME} startup` command can automatically start a selection of jails.
This comes in handy when you want to automatically start multiple jails after booting TrueNAS SCALE (e.g. from a Post Init Script). This comes in handy when you want to automatically start multiple jails after booting TrueNAS SCALE (e.g. from a Post Init Script).
""" """
) )
@ -1324,7 +1246,7 @@ def create_jail(**kwargs):
# TODO: fallback to default values for e.g. distro and release if they are not in the config file # TODO: fallback to default values for e.g. distro and release if they are not in the config file
print(f"Creating jail {jail_name} from config template {jail_config_path}.") print(f"Creating jail {jail_name} from config template {jail_config_path}.")
if jail_config_path not in config.read(jail_config_path): if jail_config_path not in config.read(jail_config_path):
eprint(f"Failed to read config config template {jail_config_path}.") eprint(f"Failed to read config template {jail_config_path}.")
return 1 return 1
else: else:
print(f"Creating jail {jail_name} with default config.") print(f"Creating jail {jail_name} with default config.")
@ -1334,7 +1256,6 @@ def create_jail(**kwargs):
for option in [ for option in [
"distro", "distro",
"docker_compatible",
"gpu_passthrough_intel", "gpu_passthrough_intel",
"gpu_passthrough_nvidia", "gpu_passthrough_nvidia",
"release", "release",
@ -1358,9 +1279,9 @@ def create_jail(**kwargs):
print( print(
dedent( dedent(
f""" f"""
TIP: Run `{SYMLINK_NAME} create` without any arguments for interactive config. TIP: Run `{COMMAND_NAME} create` without any arguments for interactive config.
Or use CLI args to override the default options. Or use CLI args to override the default options.
For more info, run: `{SYMLINK_NAME} create --help` For more info, run: `{COMMAND_NAME} create --help`
""" """
) )
) )
@ -1739,14 +1660,8 @@ def list_jails():
config = parse_config_file(get_jail_config_path(jail_name)) config = parse_config_file(get_jail_config_path(jail_name))
if config: if config:
jail["startup"] = config.my_getboolean("startup") jail["startup"] = config.my_getboolean("startup")
jail["gpu_intel"] = config.my_getboolean("gpu_passthrough_intel")
# TODO: remove gpu_passthrough in future release jail["gpu_nvidia"] = config.my_getboolean("gpu_passthrough_nvidia")
if config.my_getboolean("gpu_passthrough", False):
jail["gpu_intel"] = True
jail["gpu_nvidia"] = True
else:
jail["gpu_intel"] = config.my_getboolean("gpu_passthrough_intel")
jail["gpu_nvidia"] = config.my_getboolean("gpu_passthrough_nvidia")
if jail_name in running_machines: if jail_name in running_machines:
machine = running_machines[jail_name] machine = running_machines[jail_name]
@ -1795,133 +1710,7 @@ def list_jails():
return 0 return 0
def replace_or_add_string(file_path, regex, replacement_string):
"""
Replace all occurrences of a regular expression in a file with a given string.
Add the string to the end of the file if regex doesn't match.
Args:
file_path (str): The path to the file.
regex (str): The regular expression to search for.
replacement_string (str): The string to replace the matches with.
"""
with open(file_path, "a+") as f:
f.seek(0)
updated = False
found = False
new_text = ""
replacement_line = f"{replacement_string}\n"
for line in f:
if not re.match(regex, line):
new_text += line
continue
found = True
new_text += replacement_line
if replacement_line != line:
updated = True
if not new_text.strip():
# In case of an empty file just write the replacement_string
new_text = replacement_line
updated = True
elif not found:
# Add a newline to the end of the file in case it's not there
if not new_text.endswith("\n"):
new_text += "\n"
# Then add our replacement_string to the end of the file
new_text += replacement_line
updated = True
# Only overwrite in case there are change to the file
if updated:
f.seek(0)
f.truncate()
f.write(new_text)
return True
return False
def install_jailmaker():
# Check if command exists in path
if shutil.which("systemd-nspawn"):
print("systemd-nspawn is already installed.")
else:
print("Installing jailmaker dependencies...")
original_permissions = {}
print(
"Temporarily enable apt and dpkg (if not already enabled) to install systemd-nspawn."
)
# Make /bin/apt* and /bin/dpkg* files executable
for file in glob.glob("/bin/apt*") + (glob.glob("/bin/dpkg*")):
original_permissions[file] = os.stat(file).st_mode
stat_chmod(file, 0o755)
subprocess.run(["apt-get", "update"], check=True)
subprocess.run(["apt-get", "install", "-y", "systemd-container"], check=True)
# Restore original permissions
print("Restore permissions of apt and dpkg.")
for file, original_permission in original_permissions.items():
stat_chmod(file, original_permission)
symlink = f"/usr/local/sbin/{SYMLINK_NAME}"
if os.path.lexists(symlink) and not os.path.islink(symlink):
print(
f"Unable to create symlink at {symlink}. File already exists but is not a symlink."
)
# Check if the symlink is already pointing to the desired destination
elif os.path.realpath(symlink) != SCRIPT_PATH:
try:
Path(symlink).unlink(missing_ok=True)
os.symlink(SCRIPT_PATH, symlink)
print(f"Created symlink {symlink} to {SCRIPT_PATH}.")
except OSError as e:
if e.errno != errno.EROFS:
raise e
print(
f"Cannot create symlink because {symlink} is on a readonly filesystem."
)
alias = f"alias jlmkr='\"{SCRIPT_PATH}\"' # managed by jailmaker"
alias_regex = re.compile(r"^\s*alias jlmkr=.*# managed by jailmaker\s*")
shell_env = os.getenv("SHELL")
for shell_type in ["bash", "zsh"]:
file = "/root/.bashrc" if shell_type == "bash" else "/root/.zshrc"
if replace_or_add_string(file, alias_regex, alias):
print(f"Created {shell_type} alias {SYMLINK_NAME}.")
if shell_env.endswith(shell_type):
print(
f"Please source {file} manually for the {SYMLINK_NAME} alias to become effective immediately."
)
else:
print(f"The {shell_type} alias {SYMLINK_NAME} is already present.")
print("Done installing jailmaker.")
return 0
def startup_jails(): def startup_jails():
returncode = install_jailmaker()
if returncode != 0:
eprint("Failed to install jailmaker. Abort startup.")
return returncode
start_failure = False start_failure = False
for jail_name in get_all_jail_names(): for jail_name in get_all_jail_names():
config = parse_config_file(get_jail_config_path(jail_name)) config = parse_config_file(get_jail_config_path(jail_name))
@ -2010,11 +1799,6 @@ def main():
help="list available images to create jails from", help="list available images to create jails from",
func=run_lxc_download_script, func=run_lxc_download_script,
), ),
dict(
name="install",
help="install jailmaker dependencies and create symlink",
func=install_jailmaker,
),
dict( dict(
name="list", # name="list", #
help="list jails", help="list jails",
@ -2048,7 +1832,7 @@ def main():
), ),
dict( dict(
name="startup", name="startup",
help=f"install {SYMLINK_NAME} and startup selected jails", help="startup selected jails",
func=startup_jails, func=startup_jails,
), ),
dict( dict(
@ -2097,12 +1881,6 @@ def main():
choices=[0, 1], choices=[0, 1],
help=f"start this jail when running: {SCRIPT_NAME} startup", help=f"start this jail when running: {SCRIPT_NAME} startup",
) )
commands["create"].add_argument(
"--docker_compatible", #
type=int,
choices=[0, 1],
help="DEPRECATED",
)
commands["create"].add_argument( commands["create"].add_argument(
"--seccomp", # "--seccomp", #
type=int, type=int,

View File

@ -2,4 +2,4 @@
## Setup ## Setup
Check out the [config](./config) template file. You may provide it when asked during `jlmkr create` or, if you have the template file stored on your NAS, you may provide it directly by running `jlmkr create --start --config /mnt/tank/path/to/docker/config mydockerjail`. If you want the `nvidia-container-toolkit` to be installed, ensure you set `gpu_passthrough_nvidia=1` when creating the jail. Check out the [config](./config) template file. You may provide it when asked during `./jlmkr.py create` or, if you have the template file stored on your NAS, you may provide it directly by running `./jlmkr.py create --start --config /mnt/tank/path/to/docker/config mydockerjail`. If you want the `nvidia-container-toolkit` to be installed, ensure you set `gpu_passthrough_nvidia=1` when creating the jail.

View File

@ -6,17 +6,17 @@
## Setup ## Setup
Check out the [config](./config) template file. You may provide it when asked during `jlmkr create` or, if you have the template file stored on your NAS, you may provide it directly by running `jlmkr create --start --config /mnt/tank/path/to/incus/config myincusjail`. Check out the [config](./config) template file. You may provide it when asked during `./jlmkr.py create` or, if you have the template file stored on your NAS, you may provide it directly by running `./jlmkr.py create --start --config /mnt/tank/path/to/incus/config myincusjail`.
We manually finish the setup by running the following after creating and starting the jail: We manually finish the setup by running the following after creating and starting the jail:
```bash ```bash
jlmkr exec myincusjail bash -c 'incus admin init' ./jlmkr.py exec myincusjail bash -c 'incus admin init'
``` ```
Follow [First steps with Incus](https://linuxcontainers.org/incus/docs/main/tutorial/first_steps/). Follow [First steps with Incus](https://linuxcontainers.org/incus/docs/main/tutorial/first_steps/).
Then visit the Incus GUI inside the browser https://0.0.0.0:8443. To find out which IP address to use instead of 0.0.0.0, check the IP address for your jail with `jlmkr list`. Then visit the Incus GUI inside the browser https://0.0.0.0:8443. To find out which IP address to use instead of 0.0.0.0, check the IP address for your jail with `./jlmkr.py list`.
## Known Issues ## Known Issues

View File

@ -6,17 +6,17 @@
## Setup ## Setup
Check out the [config](./config) template file. You may provide it when asked during `jlmkr create` or, if you have the template file stored on your NAS, you may provide it directly by running `jlmkr create --start --config /mnt/tank/path/to/lxd/config mylxdjail`. Check out the [config](./config) template file. You may provide it when asked during `./jlmkr.py create` or, if you have the template file stored on your NAS, you may provide it directly by running `./jlmkr.py create --start --config /mnt/tank/path/to/lxd/config mylxdjail`.
We manually finish the setup by running the command below after creating and starting the jail. Choose the `dir` storage backend during `lxd init` and answer `yes` to "Would you like the LXD server to be available over the network?" We manually finish the setup by running the command below after creating and starting the jail. Choose the `dir` storage backend during `lxd init` and answer `yes` to "Would you like the LXD server to be available over the network?"
```bash ```bash
jlmkr exec mylxdjail bash -c 'lxd init && ./jlmkr.py exec mylxdjail bash -c 'lxd init &&
snap set lxd ui.enable=true && snap set lxd ui.enable=true &&
systemctl reload snap.lxd.daemon' systemctl reload snap.lxd.daemon'
``` ```
Then visit the `lxd` GUI inside the browser https://0.0.0.0:8443. To find out which IP address to use instead of 0.0.0.0, check the IP address for your jail with `jlmkr list`. Then visit the `lxd` GUI inside the browser https://0.0.0.0:8443. To find out which IP address to use instead of 0.0.0.0, check the IP address for your jail with `./jlmkr.py list`.
## Known Issues ## Known Issues

View File

@ -2,7 +2,7 @@
## Setup ## Setup
Check out the [config](./config) template file. You may provide it when asked during `jlmkr create` or, if you have the template file stored on your NAS, you may provide it directly by running `jlmkr create --start --config /mnt/tank/path/to/podman/config mypodmanjail`. Check out the [config](./config) template file. You may provide it when asked during `./jlmkr.py create` or, if you have the template file stored on your NAS, you may provide it directly by running `./jlmkr.py create --start --config /mnt/tank/path/to/podman/config mypodmanjail`.
## Rootless ## Rootless
@ -14,11 +14,11 @@ Check out the [config](./config) template file. You may provide it when asked du
Prerequisites: created a jail using the [config](./config) template file. Prerequisites: created a jail using the [config](./config) template file.
Run `jlmkr edit mypodmanjail` and add `--private-users=524288:65536 --private-users-ownership=chown` to `systemd_nspawn_user_args`. We start at UID 524288, as this is the [systemd range used for containers](https://github.com/systemd/systemd/blob/main/docs/UIDS-GIDS.md#summary). Run `./jlmkr.py edit mypodmanjail` and add `--private-users=524288:65536 --private-users-ownership=chown` to `systemd_nspawn_user_args`. We start at UID 524288, as this is the [systemd range used for containers](https://github.com/systemd/systemd/blob/main/docs/UIDS-GIDS.md#summary).
The `--private-users-ownership=chown` option will ensure the rootfs ownership is corrected. The `--private-users-ownership=chown` option will ensure the rootfs ownership is corrected.
After the jail has started run `jlmkr stop mypodmanjail && jlmkr edit mypodmanjail`, remove `--private-users-ownership=chown` and increase the UID range to `131072` to double the number of UIDs available in the jail. We need more than 65536 UIDs available in the jail, since rootless podman also needs to be able to map UIDs. If I leave the `--private-users-ownership=chown` option I get the following error: After the jail has started run `./jlmkr.py stop mypodmanjail && ./jlmkr.py edit mypodmanjail`, remove `--private-users-ownership=chown` and increase the UID range to `131072` to double the number of UIDs available in the jail. We need more than 65536 UIDs available in the jail, since rootless podman also needs to be able to map UIDs. If I leave the `--private-users-ownership=chown` option I get the following error:
> systemd-nspawn[678877]: Automatic UID/GID adjusting is only supported for UID/GID ranges starting at multiples of 2^16 with a range of 2^16 > systemd-nspawn[678877]: Automatic UID/GID adjusting is only supported for UID/GID ranges starting at multiples of 2^16 with a range of 2^16
@ -31,7 +31,7 @@ systemd_nspawn_user_args=--network-macvlan=eno1
--private-users=524288:131072 --private-users=524288:131072
``` ```
Start the jail with `jlmkr start mypodmanjail` and open a shell session inside the jail (as the remapped root user) with `jlmkr shell mypodmanjail`. Start the jail with `./jlmkr.py start mypodmanjail` and open a shell session inside the jail (as the remapped root user) with `./jlmkr.py shell mypodmanjail`.
Then inside the jail setup the new rootless user: Then inside the jail setup the new rootless user:
@ -61,7 +61,7 @@ exit
From the TrueNAS host, open a shell as the rootless user inside the jail. From the TrueNAS host, open a shell as the rootless user inside the jail.
```bash ```bash
jlmkr shell --uid 1000 mypodmanjail ./jlmkr.py shell --uid 1000 mypodmanjail
``` ```
Run rootless podman as user 1000. Run rootless podman as user 1000.
@ -97,7 +97,7 @@ Add `sysctl net.ipv4.ip_unprivileged_port_start=23` to the `pre_start_hook` insi
Install and enable cockpit: Install and enable cockpit:
```bash ```bash
jlmkr exec mypodmanjail bash -c "dnf -y install cockpit cockpit-podman && \ ./jlmkr.py exec mypodmanjail bash -c "dnf -y install cockpit cockpit-podman && \
systemctl enable --now cockpit.socket && \ systemctl enable --now cockpit.socket && \
ip a && ip a &&
ip route | awk '/default/ { print \$9 }'" ip route | awk '/default/ { print \$9 }'"
@ -108,7 +108,7 @@ Check the IP address of the jail and access the Cockpit web interface at https:/
If you've setup the `rootless` user, you may login with the password you've created earlier. Otherwise you'd have to add an admin user first: If you've setup the `rootless` user, you may login with the password you've created earlier. Otherwise you'd have to add an admin user first:
```bash ```bash
jlmkr exec podmantest bash -c 'adduser admin ./jlmkr.py exec podmantest bash -c 'adduser admin
passwd admin passwd admin
usermod -aG wheel admin' usermod -aG wheel admin'
``` ```