#!/bin/bash #Usage: /usr/bin/qwdctl controls the availability of virtual machines for the qemu-web-desktop. # # Each entry in the configuration file '/etc/qemu-web-desktop/machines.conf' # spans on 1 to 3 lines: # # - [name.ext or URL or file path] # - url=[URL to ISO, QCOW2, VDI, VMDK, RAW, VHD/VHDX, QED virtual machine disk, optional] # - description=[description to be shown in the service page] # # Images listed in the configuration file without a 'url=' parameter are # expected to be downloaded by hand and installed into # '/var/lib/qemu-web-desktop/machines' by the local administrator. Then, just # specify the [name.ext] and description. # When the description is missing, the VM file name is used. # Additional machine descriptions can be given in '/etc/qemu-web-desktop/config.d/*.ini' files. # # use: 'qwdctl help' to get help about usage and commands/options. set -eo pipefail # identify type of system case "$(uname -s)" in Darwin) DIST=Darwin ;; # macOS Linux) if [ -e "$PREFIX/etc/initramfs-tools/modules" ]; then DIST=Debian else DIST=Arch fi ;; *) DIST=Unknown echo "WARNING: Unsupported system" ;; esac bin=$(dirname $0) p=$(basename $0) if command -v brew 2>&1 >/dev/null; then # using brew / Apple Mac PREFIX=`brew --prefix` GREP=$(command -v ggrep || command -v grep) # Use GNU grep if available EDITOR=nano else GREP=grep fi # check required binaries for cmd in wget sed awk "$GREP" "${EDITOR:-nano}"; do command -v "$cmd" >/dev/null || { echo "$p: ERROR: $cmd not found"; exit 1; } done # After setting PREFIX if [[ -z "$PREFIX" ]]; then PREFIX="" elif [[ ! "$PREFIX" =~ ^/ ]]; then echo "$p: ERROR: Invalid PREFIX: $PREFIX" >&2 exit 1 fi # files to process F="$PREFIX/etc/qemu-web-desktop/machines.conf" machine_conf="$F" if [ ! -f "$F" ]; then echo "$p: WARNING: can not find QWD machine.conf file ($F)." fi conf_d="$PREFIX/etc/qemu-web-desktop/config.d" F="$PREFIX/usr/share/qemu-web-desktop/html/desktop/index.html" index_html="$F" if [ -f $PREFIX/var/www/qemu-web-desktop/html/desktop/index.html ]; then index_html="$PREFIX/var/www/qemu-web-desktop/html/desktop/index.html" elif [ ! -f "$F" ]; then echo "$p: WARNING: can not find QWD index.html file ($F)." fi # set to yes if apache/httpd include_module does not properly show list in index.html for i in $*; do case "$i" in --machine-insert|--machine_insert|machine-insert|machine_insert) QWDCTL_INSERT=yes # for refresh/download ;; --yes|-y) QWDCTL_YES=1 # assume Yes for gpu and purge ;; esac done # generated files, should be linked into /usr/share/qemu-web-desktop/html/desktop/ F="$PREFIX/var/lib/qemu-web-desktop" qwdprefix="$F" if [ ! -d "$F" ]; then echo "$p: WARNING: can not find QWD machines directory ($F)." fi machine_html="$qwdprefix/machines.html" # search for local config if [ -f "$bin/../config.pl" ]; then # using local configuration echo "$bin/../config.pl" config_pl=$(realpath "$bin/../config.pl") else F="$PREFIX/etc/qemu-web-desktop/config.pl" config_pl="$F" if [ ! -f "$F" ]; then echo "$p: WARNING: can not find QWD config.pl file ($F)." fi fi # search for local cgi/.pl script if [ -x "$bin/../cgi-bin/qemu-web-desktop.pl" ]; then cgi=$(realpath "$bin/../cgi-bin/qemu-web-desktop.pl") elif [ -x "$cgi/qemu-web-desktop.pl" ]; then # local (git) cgi="$cgi/qemu-web-desktop.pl" elif [ -x "$PREFIX/srv/http/cgi-bin/qemu-web-desktop.pl" ]; then # Arch/httpd default cgi="$PREFIX/srv/http/cgi-bin/qemu-web-desktop.pl" elif [ -x "$PREFIX/var/www/cgi-bin/qemu-web-desktop.pl" ]; then # RedHat/httpd and Brew default cgi="$PREFIX/var/www/cgi-bin/qemu-web-desktop.pl" else # Debian default cgi="$PREFIX/usr/lib/cgi-bin/qemu-web-desktop.pl" fi # ------------------------------------------------------------------------------ # Clean HTML string # ret=$(escape_html "string") escape_html() { local s="$1" s="${s//&/&}" s="${s///>}" s="${s//\"/"}" #' s="${s//\'/'}" printf '%s' "$s" } # List all section names in an INI file (one per line) # sections=$(ini_sections "ini_file") # # Replaces: confget -f $F -q sections # Replaces: crudini --get $F ini_sections() { local f="$1" awk ' /^[ \t]*[;#]/ { next } # skip comment lines /^[ \t]*\[.*\][ \t]*$/ { line=$0 gsub(/^[ \t]*\[[ \t]*/, "", line) gsub(/[ \t]*\][ \t]*$/, "", line) print line } ' "$f" } # Get the value of key "$3" in section "$2" of file "$1" # value = $(ini_get "ini_file" "section" "key") # # Replaces: confget -f $F -s $i url # Replaces: crudini --get $F $i url ini_get() { local f="$1" section="$2" key="$3" awk -v section="$section" -v key="$key" ' function trim(s) { gsub(/^[ \t]+|[ \t]+$/, "", s) return s } /^[ \t]*[;#]/ { next } # skip comment lines /^[ \t]*\[.*\][ \t]*$/ { line=$0 gsub(/^[ \t]*\[[ \t]*/, "", line) gsub(/[ \t]*\][ \t]*$/, "", line) in_sec = (line == section) next } in_sec { line = $0 eq = index(line, "=") if (eq > 0) { k = trim(substr(line, 1, eq-1)) if (k == key) { v = trim(substr(line, eq+1)) # strip surrounding quotes if present, like crudini does if (v ~ /^".*"$/ || v ~ /^\x27.*\x27$/) { v = substr(v, 2, length(v)-2) } print v exit } } } ' "$f" } # List running sessions qwdctl_status() { echo "$p status" echo " config: $config_pl" echo " $conf_d/" echo " machines: $machine_conf" echo " $machine_html" echo " $qwdprefix/machines/" echo " landing: $index_html" if [[ "$DIST" == "Darwin" ]]; then ip_address=$(ifconfig | grep "inet " | grep -v 127.0.0.1 | awk '{print $2}' | head -1) else ip_address=$(hostname -I | awk '{print $1}') fi echo " service: http://$ip_address/qemu-web-desktop/" echo " " # Loop through machine lists local active_sections=() local inactive_sections=() local files=("$machine_conf" "$conf_d"/*.ini "$conf_d"/*.conf) for F in "${files[@]}"; do # Skip if the file does not exist (e.g., no .ini or .conf files) [ -f "$F" ] || continue # Extract active sections while IFS= read -r section; do active_sections+=("$section") done < <(grep -E '^\[[^]]+\]' "$F" | sed -E 's/^\[([^]]+)\]/\1/') # Extract inactive sections while IFS= read -r section; do inactive_sections+=("$section") done < <(grep -E '^;\[[^]]+\]' "$F" | sed -E 's/^;\[([^]]+)\]/\1/') done if [ -z "${active_sections[*]}" ]; then echo "Enabled machines (use '$p enable VM|FILE|URL' to add one):" echo " None" else echo "Enabled machines (disable with '$p disable VM'):" printf ' %s\n' "${active_sections[@]}" fi echo if [ ! -z "${inactive_sections[*]}" ]; then echo "Disabled machines (enable with '$p enable VM')" printf ' %s\n' "${inactive_sections[@]}" echo fi local orphan=0 echo "Orphan machine files (not enabled/disabled, purge with '$p purge VM'):" for file in "$qwdprefix/machines"/*; do [ -f "$file" ] || continue filename=$(basename "$file") # Check if filename is not in active or inactive lists if ! printf '%s\n' "${active_sections[@]}" "${inactive_sections[@]}" | grep -q "^${filename}$"; then orphan=1 echo " $filename" fi done if [ $orphan == 0 ]; then echo " None"; fi echo " " echo "Running sessions:" # Header for the table printf "%-8s | %5s | %-15s | %4s | %6s | %-7s | %s\n" "PID" "CPU/%" "User name" "#CPU" "MEM/GB" "GPU" "Full name" printf "%s\n" "------------------------------------------------------------------------" # Get PIDs for qemu-system, excluding grep and sh -c processes ps auxww | grep 'qemu-system' | grep -v 'grep' | grep -v 'sh -c' | while read -r line; do # Extract PID and CPU usage pid=$(echo "$line" | awk '{print $2}') cpu_usage=$(echo "$line" | awk '{print $3"%"}') # Extract the full command (from field 11 onwards) cmd=$(echo "$line" | awk '{for(i=11;i<=NF;i++) printf $i" "; print ""}') # Use GNU grep for Perl regex support full_name=$(echo "$cmd" | $GREP -oP '(?<=-name ).*?(?= -|$)') nb_cpu=$(echo "$cmd" | $GREP -oP '(?<=-smp ).*?(?= -|$)') mem_mb=$(echo "$cmd" | $GREP -oP '(?<=-m ).*?(?= -|$)') mem_gb=$(awk -v mem_mb="${mem_mb:-0}" 'BEGIN {printf "%.2f", mem_mb / 1024}') user_name=$(echo "$full_name" | cut -d: -f2) pci=$(echo "$cmd" | $GREP -oP '(?<=host=)[^, ]+' || echo "") # Print the row printf "%-8s | %5s | %-15s | %4s | %6s | %-7s | %s\n" "$pid" "$cpu_usage" "$user_name" "$nb_cpu" "$mem_gb" "$pci" "$full_name" done } # Enable/disable a section in $index_html # toggle_section "enable"|"disable" "GPU checkbox"|"one-shot session checkbox" toggle_section() { local action="$1" marker="$2" t=$(mktemp -t "index_html.XXXXXX") chmod 644 "$t" awk -v action="$action" -v marker="$marker" ' { if (in_section) { if ($0 ~ /^$/) { in_section = 0 } else if (skip_lines > 0) { skip_lines-- } else if ($0 ~ /$/, "") } else { if ($0 !~ /^$/) $0 = $0 " -->" } } } else if ($0 ~ "" \ -v end="" \ -v replacement="$replacement" ' BEGIN { in_block = 0 } # Check for the START marker $0 == start { in_block = 1 print start # Print the start marker print replacement replacement = "" next } # Check for the END marker $0 == end { in_block = 0 print end # Print the end marker next } # If inside the block, print the replacement content and skip original line in_block { # the replqcement has already been printed after START next # Skip printing the original content } # If not in the block, print the line normally !in_block { print $0 } ' "$index_html" > "$t" mv "$t" "$index_html" || { echo "ERROR: Failed to move $t" >&2; exit 1; } chmod a+r "$index_html" fi ;; # ------------------------------------------------------------------------------ --stop|stop) # stop sessions matching TOKEN. Some snapshot files may be left-over. if [ "x$2" = "x" ]; then echo "$p: Stopping all local VMs" $cgi --service_purge=1 --dir_snapshots=/tmp --dir_cfg=/tmp 2>&1 | $GREP -i "stop" exit 0 fi validate_input "$2" || exit 1 t=$(ps aux | $GREP -F qemu-web-desktop | $GREP -F -- "$2") name=$(echo "$t" | $GREP -oP '(?<=\-name )[^ ]*' ) pid=$( echo "$t" | awk '{ print $2 }' ) [[ -n "$pid" ]] || { echo "$p: ERROR: No matching process found" >&2; exit 1; } table=$(printf '%s\n' "$name" | pr -1 -Ts'\t') u=$(echo "$table" | uniq ) echo "$p: Stopping:" echo "$u" kill -- "$pid" ;; # ------------------------------------------------------------------------------ --purge|purge) # clean unused and disabled VM files. VM="$2" # optional name of VM file to match validate_input "$2" || exit 1 # scan VM files in $qwdprefix/machines for F in "$qwdprefix/machines"/*; do b=$(basename "$F") if [ ! -f "$F" ]; then continue; fi # when VM is given, we must only check when F == VM if [[ -n "$VM" && ! "$b" == "$VM"* ]]; then continue fi # continue $F is currently running if [[ "$DIST" != "Darwin" ]]; then t=$(ps -u _qemu-web-desktop -o comm= | $GREP -qF -- "$b") else t=$(ps auxw | $GREP -qF -- "$b") fi if [ "$t" ]; then echo "$p: VM $b is running as: $t" continue fi # or $F if is active (not commented) in machine conf FOUND=no for C in $machine_conf $conf_d/*.ini $conf_d/*.conf; do if [ ! -f "$C" ]; then continue; fi l=$($GREP -v '^;' $C) if [[ "$l" == *"$b"* ]];then FOUND=yes echo "$p: VM $b is enabled in $C" continue fi done if [ "$FOUND" = "yes" ]; then continue fi # now remove $F if [ -z "$QWDCTL_YES" ]; then read -p ">> Remove inactive $F (y/N)?" choice case "$choice" in y|Y ) echo "Proceeding";; *) echo "Keeping." && continue;; esac fi rm -f -- "$F" done ;; # ------------------------------------------------------------------------------ *) echo "Usage: $p [help|download|refresh|status|start VM|stop|gpu|gpu-unlock|enable VM|disable VM|purge|edit] ..." exit 0 esac # ------------------------------------------------------------------------------