[TUTORIAL] LXC No GPU Desktop + USB Passthrough

Giggling3999

Member
Apr 2, 2024
93
7
13
I've been on a quest to move over some of my VM into LXC which has proven more difficult than expected because I neither want to buy a GPU, nor having it using power 24/7, so software rendering is what I wanted.

Obviously this is much easier with a VM, but I do have it working and came up with a script to even pass through USB like I would do with Spice, usually. It has been good for learning if nothing else.

There is actually quite a few tutorials to set up using xrdp. General steps are...Setup LXC...Create a user, install yay....
(Cinnamon desktop chosen for X11 support)

Code:
pacman -S xorg-xauth cinnamon xfce-terminal
su lxcuser
yay xrdp
yay xorgxrdp
su root
adduser xrdp ssl-cert
systemctl enable --now xrdp

su lxcuser
cat > ~/.xinitrc <<'EOF'
#!/bin/sh
export XDG_CURRENT_DESKTOP=X-Cinnamon
export XDG_SESSION_DESKTOP=cinnamon
export DESKTOP_SESSION=cinnamon
export XDG_SESSION_TYPE=x11
exec cinnamon-session
EOF

chmod +x ~/.xinitrc

yay -S pipewire-module-xrdp
sudo nano /etc/polkit-1/rules.d/45-allow-colord.rules
###
polkit.addRule(function(action, subject) {
    if (action.id.indexOf("org.freedesktop.color-manager.") == 0 &&
        subject.isInGroup("wheel")) {
        return polkit.Result.YES;
    }
});

After that here is a script I am using to send over local or server USB devices to a running LXC (Vibed + Reviewed, I am not great with bash). It does contain a readme for general setup required (usbip package, sudoers commands, ssh cert). I've only been using a few days so it may get adjusted

Code:
#!/bin/bash
#### VARIABLES TO SET
ReadMe="
            This script is designed to redirect/Map either local or server USB devices into an LXC
            It is meant to run against an already running LXC as the easiest way to manage /dev# devices is to delete instantly after adding.
            This does however mean that it does not work against stopped LXC as they are removed instantly
            (The script takes advantage that maps are not removed until the LXC is shut down - This could potentially lead to an issue with 100s of mapping prior to a shutdown )
            Requirements to run:
            Local Device:
            The following should be added to /etc/suderos:
            Remember - More specific commands can increase security of what can be run
            *Potentially Dangerous*
            localUserName ALL=(root) NOPASSWD: /usr/bin/modprobe usbip_host
            localUserName ALL=(root) NOPASSWD: /usr/bin/systemctl enable --now usbipd
            localUserName ALL=(root) NOPASSWD: /usr/bin/usbip bind -b *
            localUserName ALL=(root) NOPASSWD: /usr/bin/usbip unbind -b *
            Install usbip package
            Already tested SSH into proxmox server as usbredirect profile - So the certificate is accepted
            i.e. ssh  -i ~/.ssh/usbredirect usbredirect@proxserv

            Server Device:
            The following should be added to /etc/suderos:
            Remember - More specific commands can increase security of what can be run
            *Potentially Dangerous*
            usbredirect ALL=(root) NOPASSWD: /usr/sbin/usbip attach -r *
            usbredirect ALL=(root) NOPASSWD: /usr/sbin/usbip detach -p *
            usbredirect ALL=(root) NOPASSWD: /usr/sbin/pct set 114 --dev* *
            usbredirect ALL=(root) NOPASSWD: /usr/sbin/pct set 114 --delete dev*
            usbredirect ALL=(root) NOPASSWD: /usr/sbin/modprobe vhci_hcd
            usbredirect ALL=(root) NOPASSWD: /usr/bin/cat /etc/pve/lxc/114.conf
            Install usbip package
            "
           
PROXMOX_HOST="proxmoxserver.local"
PROXMOX_USER="usbredirect"
PROXMOX_KEY="$HOME/.ssh/usbredirect"
CTID="114"
CTUSERID="1000"
CTGID="0"
CTMAPPEDMODE="0660"
USB_SERVER_HOST=$(hostnamectl --static)
echo "hostname for attach: $USB_SERVER_HOST"
SSH=(
    ssh
    -i "$PROXMOX_KEY"
    -o BatchMode=yes
    -o ConnectTimeout=10
    "$PROXMOX_USER@$PROXMOX_HOST"
)

#### FUNCTIONS ####
InformUser()
{
    echo ""
    echo "-------------------------"
    echo ""
    echo "$1"
    zenity --notification --text="$1"
}
InformError()
{
    echo ""
    echo "-------------------------"
    echo ""
    echo "Error: $1"
    zenity --error \
        --title="USB Redirect Error" \
        --text="$1"
    exit 1
}
ListUsbDevices()
{
    local DEVICE_LOCATION="$1"
    for usb in /sys/bus/usb/devices/*; do
        [[ -r "$usb/idVendor" ]] || continue
        [[ -r "$usb/idProduct" ]] || continue
        [[ -r "$usb/busnum" ]] || continue
        [[ -r "$usb/devnum" ]] || continue
        usb="$(readlink -f "$usb")"
        if [[ "$DEVICE_LOCATION" == "Server device" ]]; then
            # Exclude devices imported into Proxmox through USB/IP.
            case "$usb" in
                */vhci_hcd*/*)
                    continue
                    ;;
            esac
        fi
        VID="$(cat "$usb/idVendor")"
        PID="$(cat "$usb/idProduct")"
        BUSNUM="$((10#$(cat "$usb/busnum")))"
        DEVNUM="$((10#$(cat "$usb/devnum")))"
        BUSID="$(basename "$usb")"
        USBID="$VID:$PID"
        DESCRIPTION=$(
            /usr/bin/lsusb -s "$BUSNUM:$DEVNUM" |
                sed -E \
                    's/^Bus [0-9]+ Device [0-9]+: ID [0-9a-fA-F]+:[0-9a-fA-F]+[[:space:]]*//'
        )
        if [[ "$DEVICE_LOCATION" == "Local device" ]]; then
            DRIVER="$(basename "$(readlink -f "$usb/driver" 2>/dev/null)")"
            if [[ "$DRIVER" == "usbip-host" ]]; then
                STATUS="Exported"
            else
                STATUS="Available"
            fi
        else
            STATUS="Remote"
        fi
        printf '%s\t%s\t%s\t%s\n' \
            "$BUSID" \
            "$USBID" \
            "$DESCRIPTION" \
            "$STATUS"
    done
}

# Find all device paths so each can be mapped.
FindDevicePaths()
{
    local VID="${1,,}"
    local PID="${2,,}"
    local usb
    local class
    local target
    local dev
    for usb in /sys/bus/usb/devices/*; do
        [[ -r "$usb/idVendor" ]] || continue
        [[ -r "$usb/idProduct" ]] || continue
        [[ "$(cat "$usb/idVendor")" == "$VID" ]] || continue
        [[ "$(cat "$usb/idProduct")" == "$PID" ]] || continue
        usb="$(readlink -f "$usb")"
        if [[ -r "$usb/busnum" && -r "$usb/devnum" ]]; then
            printf '/dev/bus/usb/%03d/%03d\n' \
                "$((10#$(cat "$usb/busnum")))" \
                "$((10#$(cat "$usb/devnum")))"
        fi
        for class in /sys/class/*/*; do
            [[ -e "$class" ]] || continue
            target="$(readlink -f "$class")"
            case "$target" in
                "$usb"|"$usb"/*)
                    dev="/dev/$(basename "$(dirname "$class")")/$(basename "$class")"
                    [[ -e "$dev" ]] && echo "$dev"
                    dev="/dev/$(basename "$class")"
                    [[ -e "$dev" ]] && echo "$dev"
                    dev="/dev/snd/$(basename "$class")"
                    [[ -e "$dev" ]] && echo "$dev"
                    ;;
            esac
        done
    done | sort -u
}
#### START ####
#### CHOOSE LOCAL OR SERVER DEVICE ####
DEVICE_LOCATION=$(
    zenity --list \
        --title="USB Redirect" \
        --width=450 \
        --height=305 \
        --column="Device location" \
        "Read Me" \
        "Local device" \
        "Server device" \
       
)
# Cancel pressed
[[ -n "$DEVICE_LOCATION" ]] || exit 0

#### BUILD DEVICE LIST ####
ROWS=()
if [[ "$DEVICE_LOCATION" == "Local device" ]]; then
    DEVICE_LIST=$(ListUsbDevices "Local device")
elif [[ "$DEVICE_LOCATION" == "Server device" ]]; then
    DEVICE_LIST=$(
        {
            declare -f ListUsbDevices
            printf '%s\n' 'ListUsbDevices "Server device"'
        } | "${SSH[@]}" /usr/bin/bash
    )
else
        zenity --info \
        --title="USB Redirector - Read me" \
        --width=1250 \
        --height=400 \
        --text="$ReadMe"
        exit 0
fi
LIST_STATUS=$?
if (( LIST_STATUS != 0 )); then
    InformError "Failed to obtain the USB device list."
fi
while IFS=$'\t' read -r BUSID USBID DESCRIPTION STATUS; do
    [[ -n "$BUSID" && -n "$USBID" ]] || continue
    ROWS+=(
        "$BUSID"
        "$USBID"
        "$DESCRIPTION"
        "$STATUS"
    )
done <<< "$DEVICE_LIST"
if (( ${#ROWS[@]} == 0 )); then
    InformError "No USB devices were found."
fi

#### CHOOSE USB DEVICE ####
CHOICE=$(
    zenity --list \
        --title="Choose USB Device" \
        --width=750 \
        --height=400 \
        --column="Bus ID" \
        --column="USB ID" \
        --column="Device" \
        --column="Status" \
        "${ROWS[@]}"
)
# Cancel pressed
[[ -n "$CHOICE" ]] || exit 0
BUSID="$CHOICE"
# Determine VID:PID corresponding to the selected bus
USBID=""
for ((i=0; i<${#ROWS[@]}; i+=4)); do
    if [[ "${ROWS[i]}" == "$BUSID" ]]; then
        USBID="${ROWS[i+1]}"
        DESCRIPTION="${ROWS[i+2]}"
        STATUS="${ROWS[i+3]}"
        break
    fi
done
if [[ -z "$USBID" ]]; then
    InformError "Could not determine the USB ID for $BUSID."
fi

#### LOCAL DEVICE: INITIALISE USB/IP ####
if [[ "$DEVICE_LOCATION" == "Local device" ]]; then
    if [[ "$STATUS" == "Exported" ]]; then
        ERROR=$(sudo -n /usr/bin/usbip unbind -b "$BUSID" 2>&1)
        RESULT=$?
        if (( RESULT != 0 )); then
            InformError "Failed to stop exporting $DESCRIPTION. $ERROR"
        fi
        InformUser "USB device no longer exported."
        exit 0
    else
        ERROR=""
        if ! OUTPUT=$(sudo -n /usr/bin/systemctl enable --now usbipd 2>&1); then
            InformError "Failed to start usbipd: $OUTPUT"
        elif ! OUTPUT=$(sudo -n /usr/bin/modprobe usbip_host 2>&1); then
            InformError "Failed to load usbip_host: $OUTPUT"
        elif ! OUTPUT=$(sudo -n /usr/bin/usbip bind -b "$BUSID" 2>&1); then
            InformError "Failed to export USB device: $OUTPUT"
        fi
        if [[ -n "$ERROR" ]]; then
            InformError "$ERROR"
        fi
        InformUser "USB device exported."$'\n'"Device: $DESCRIPTION"$'\n'"Bus ID: $BUSID"$'\n'"USB ID: $USBID"
    fi

    #### SERVER SIDE: ATTACH USB/IP DEVICE ####
    if ! ATTACH_RESULT=$(
        "${SSH[@]}" "sudo -n /usr/sbin/modprobe vhci_hcd && sudo -n /usr/sbin/usbip attach \
            -r '$USB_SERVER_HOST' \
            -b '$BUSID'" 2>&1
    ); then
        InformError "Proxmox failed to attach USB device $BUSID. $ATTACH_RESULT"
    fi
    # Give udev time to create video, hidraw, input, tty and other nodes.
    sleep 1
fi

# Local device:
#   Exported locally and attached to Proxmox through USB/IP.
#
# Server device:
#   Already physically present on Proxmox.
VID="${USBID%%:*}"
PID="${USBID##*:}"
VID="${VID,,}"
PID="${PID,,}"
echo "Searching Proxmox for USB device $VID:$PID"
DEVICE_PATHS=$(
    {
        declare -f FindDevicePaths
        printf '%s\n' 'FindDevicePaths "$1" "$2"'
    } |
        "${SSH[@]}" /usr/bin/bash -s -- "$VID" "$PID"
)
DISCOVERY_RESULT=$?
echo "Discovery exit status: $DISCOVERY_RESULT"
echo "Discovered paths:"
printf '%s\n' "$DEVICE_PATHS"
if (( DISCOVERY_RESULT != 0 )) || [[ -z "$DEVICE_PATHS" ]]; then
    InformError "No device nodes were found."
fi
InformUser "Found these Proxmox paths for $VID:$PID: $DEVICE_PATHS"

#### SERVER SIDE: GET CURRENT CT CONFIGURATION ####
if ! CT_CONFIG=$(
    "${SSH[@]}" sudo -n /usr/bin/cat /etc/pve/lxc/$CTID.conf 2>&1
); then
    InformError "Could not read the configuration for CT $CTID. $CT_CONFIG"
fi

#### SERVER SIDE: MAP EACH DISCOVERED DEVICE ####
mapfile -t DEVICES <<< "$DEVICE_PATHS"
echo "Device count: ${#DEVICES[@]}"
for DEVICE in "${DEVICES[@]}"; do
    echo "DEVICE=[$DEVICE]"
done
MAPPED_DEVICES=""
LAST_DEV=$(
    grep -oE '^dev[0-9]+' <<< "$CT_CONFIG" |
    sed 's/dev//' |
    sort -n |
    tail -1
)
[[ -n "$LAST_DEV" ]] || LAST_DEV=-1
NEXT_DEV=$((LAST_DEV + 1))
for DEVICE in "${DEVICES[@]}"; do
    [[ -n "$DEVICE" ]] || continue
    SLOT="dev$NEXT_DEV"
    NEXT_DEV=$((NEXT_DEV + 1))
    echo "Attempting: $SLOT -> $DEVICE"
    MAP_RESULT=$(
        "${SSH[@]}" sudo -n /usr/sbin/pct set "$CTID" \
            "--$SLOT" \
            "$DEVICE,uid=$CTUSERID,gid=$CTGID,mode=$CTMAPPEDMODE" 2>&1
    )
    MAP_STATUS=$?
    if (( MAP_STATUS == 0 )); then
        MAPPED_DEVICES+="$SLOT -> $DEVICE"$'\n'
    else
        MAPPED_DEVICES+="$SLOT -> $DEVICE (warning)"$'\n'
        echo "Mapping warning for $SLOT -> $DEVICE:" >&2
        echo "$MAP_RESULT" >&2
        echo ""
        echo "-------------------------"
        echo ""
    fi
    # Immediately schedule this temporary mapping for removal
    # at the next CT restart.
    DELETE_RESULT=$(
        "${SSH[@]}" sudo -n /usr/sbin/pct set "$CTID" \
            --delete "$SLOT" 2>&1
    )
    DELETE_STATUS=$?
    if (( DELETE_STATUS == 0 )); then
        MAPPED_DEVICES+="  removal scheduled for reboot"$'\n'
    else
        echo "Could not schedule deletion of $SLOT:" >&2
        echo "$DELETE_RESULT" >&2
    fi
done

#### SUCCESS ####
InformUser "Device passthrough appears successful."$'\n'"Device: $DESCRIPTION"$'\n'"Bus ID: $BUSID"$'\n'"USB ID: $USBID"$'\n'"MAPPED PATHS: $MAPPED_DEVICES"
 
Last edited: