Virsh & Virt-Install Memo

1. Instances

1.1 Control instances

virsh list --all          # List all
virsh start <instance>
virsh shutdown <instance>
virsh destroy <instance>
virsh suspend <instance>
virsh resume <instance>
virsh reboot <instance>
virsh undefine <instance>
virsh console <instance>  # Ctrl-] to leave
virsh vncdisplay <instance>  # display vnc port number

To use console tty, use --console pty,target_type=serial to create vm or modify vm configure to

<serial type='pty'>
<target port='0'/>
<console type='pty'>
<target type='serial' port='0'/>

and add console=ttyS0 to kernel parameter by edit the /etc/default/grub file, add console=ttyS0 to the GRUB_CMDLINE_LINUX variable and execute # grub-mkconfig -o /boot/grub/grub.cfg.

1.2 Define instances

virsh dumpxml <instance> >dump.xml
virsh create dump.xml   # Create from XML
virsh edit <instance>
virsh undefine <instance>

virsh blockresize <instance> --path vda --size 100G

1.3 Modify instances

Add NIC to instance(REF):

virsh domiflist vm1
virsh attach-interface --domain vm1 --type network \
--source openstackvms --model virtio \
--mac 52:54:00:4b:73:5f --config --live
virsh detach-interface --domain vm1 --type network \
--mac 52:53:00:4b:75:5f --config

Show IP address of instances on ubuntu 16.04:

cat /var/lib/libvirt/dnsmasq/virbr0.status

2. Hypervisor

virsh dominfo
virsh vcpuinfo
virsh nodeinfo

3. Virt-Install

Installing Virtual Machines with virt-install, plus copy pastable distro install one-liners

4. Virt-Clone

virt-clone -o old_vm -n new_vm -f /data/new_vm.qcow2

5. snapshot

virsh snapshot-create-as VM_NAME SNAPSHOT_TAG  # live snaphost if vm running
virsh snapshot-create-as VM_NAME SNAPSHOT_TAG  # internal disk snapshot if vm shutdown
virsh snapshot-create-as VM_NAME SNAPSHOT_TAG --disk-only --atomic  # internal disk snapshot
virsh snapshot-revert VM_NAME SNAPSHOT_TAG --running

export vm with snapshot:

# export
virsh snapshot-dumpxml VM_NAME SNAPSHOT_TAG --security-info > vm_snapshot_tag.xml # do on every snapshot

# import
virsh snapshot-create VM_NAME vm_snapshot_tag.xml --redefine --current

6. network

assign static ip to vm:

virsh dumpxml VM_NAME | grep mac
virsh net-update default add-last ip-dhcp-host \
--xml "<host mac='52:54:00:XX:XX:XX' ip='192.168.122.XXX'/>" \
--live --config

7. fsck qcow2

use nbd (network block device) kernel module to fix filesystem in qcow2:

sudo modprobe nbd max_part=8

sudo qemu-nbd --connect=/dev/nbd0 /mnt/kvm/wordpress-sites.qcow2

sudo parted /dev/nbd0 print
sudo fsck /dev/nbd0p1

sudo qemu-nbd --disconnect /dev/nbd0