vm.sh (2873B)
1 #!/usr/bin/env bash 2 # The test VM: QEMU with KVM and UEFI, booting out/disk.raw, with the empty 3 # out/data.qcow2 as a second disk and SSH on localhost:2222. 4 # 5 # vm/vm.sh start boot it in the background; the serial console goes to out/serial.log 6 # vm/vm.sh console boot it in the foreground on this terminal (Ctrl-a x quits) 7 # vm/vm.sh ssh [cmd] a shell (or a command) as root 8 # vm/vm.sh wait wait until SSH answers 9 # vm/vm.sh view its screen, in a VNC viewer (it's on localhost:5901) 10 # vm/vm.sh screenshot [file.png] its screen, saved (default out/screen.png) 11 # vm/vm.sh log follow the serial console 12 # vm/vm.sh stop power it off 13 source "$(dirname "$0")/common.sh" 14 15 qemu_args() { 16 [[ -f "$OVMF_VARS" ]] || cp "$OVMF_VARS_TEMPLATE" "$OVMF_VARS" 17 printf '%s\n' \ 18 -enable-kvm -cpu host -m 4096 -smp 4 \ 19 -machine q35 \ 20 -drive "if=pflash,format=raw,readonly=on,file=$OVMF_CODE" \ 21 -drive "if=pflash,format=raw,file=$OVMF_VARS" \ 22 -drive "file=$DISK,format=raw,if=virtio" \ 23 -drive "file=$DATA,format=qcow2,if=none,id=data" \ 24 -device virtio-blk-pci,drive=data,serial=patina-data \ 25 -nic "user,model=virtio-net-pci,hostfwd=tcp:127.0.0.1:$SSH_PORT-:22" \ 26 -device virtio-vga -vnc "127.0.0.1:$VNC_DISPLAY" \ 27 -device qemu-xhci -device usb-tablet -device usb-kbd \ 28 -monitor "unix:$MONITOR,server,nowait" 29 } 30 31 need_disk() { [[ -f "$DISK" ]] || die "no $DISK; vm/disk.sh first"; } 32 33 case "${1:-}" in 34 start) 35 need_disk 36 vm_running && die "already running" 37 mapfile -t args < <(qemu_args) 38 qemu-system-x86_64 "${args[@]}" \ 39 -display none -serial "file:$SERIAL_LOG" \ 40 -daemonize -pidfile "$PIDFILE" 41 say "started; vm/vm.sh wait, then vm/vm.sh ssh" 42 ;; 43 console) 44 need_disk 45 vm_running && die "already running" 46 mapfile -t args < <(qemu_args) 47 exec qemu-system-x86_64 "${args[@]}" -nographic 48 ;; 49 ssh) 50 shift 51 vm_ssh "$@" 52 ;; 53 wait) 54 vm_running || die "not running" 55 for _ in $(seq 1 120); do 56 vm_ssh true 2>/dev/null && { say "up"; exit 0; } 57 vm_running || die "QEMU exited; see $SERIAL_LOG" 58 sleep 2 59 done 60 die "no SSH after 4 minutes; see $SERIAL_LOG" 61 ;; 62 view) 63 vm_running || die "not running" 64 exec vncviewer "127.0.0.1:$((5900 + VNC_DISPLAY))" 65 ;; 66 screenshot) 67 vm_running || die "not running" 68 shot=${2:-$OUT/screen.png} 69 rm -f "$shot" 70 printf 'screendump %s -f png\n' "$shot" | nc -U -q 1 "$MONITOR" >/dev/null 71 for _ in $(seq 1 20); do [[ -s "$shot" ]] && break; sleep 0.2; done 72 [[ -s "$shot" ]] || die "no screenshot" 73 echo "$shot" 74 ;; 75 log) 76 exec tail -f "$SERIAL_LOG" 77 ;; 78 stop) 79 vm_running || exit 0 80 kill "$(cat "$PIDFILE")" 81 rm -f "$PIDFILE" 82 say "stopped" 83 ;; 84 *) 85 sed -n '2,12p' "$0" | sed 's/^# \{0,1\}//' 86 exit 1 87 ;; 88 esac