Basic KVM operations

From Newroco Tech Docs
Jump to navigationJump to search

SEE ALSO!

List all the VMs, and see which ones are running

# sudo virsh list --all

Start, stop, reboot a VM

Start

You can list the VMs first, then:

# sudo virsh start <name of your vm>

Shutdown

Note: this require the VM to have support for ACPI - at the moment it doesn't seem to work with windows VMs (seems OK to me- Jo).

# sudo virsh shutdown <name of the vm>


Reboot

# virsh reboot <name of the vm>

Destroy

Same thing as taking the plug off. Use with care.

# sudo virsh destroy <name of the vm>

Guest start on boot ( Autostart )

sudo virsh autostart $VM_ID
or
sudo virsh autostart --disable $VM_ID

Delete a VM

THIS REMOVES A VM. NO RESTORE POSSIBLE. PLEASE USE WITH SPECIAL CARE.

sudo virsh shutdown <name of the vm>
sudo virsh undefine <name of the vm>
sudo rm -rf /var/lib/kvm/<name of the vm>

Remove from salt

sudo salt-key -L | grep <VM NAME> 
sudo salt-key -d <FULL VM NAME>

Remove etc/hosts # just for newroco server

vi /etc/hosts
# find the VM and delete the name and ip

Remove From zabbix

Search for <VM NAME> and them click on delete

Back up a VM

After shutting down:

# cd /var/lib/kvm
# cp -R <name of the vm> /to/safe/place

Copy or move a VM to another host

Copy the VM image to remote server in /tmp dir (make sure the VM is shutdown):

rsync /var/lib/kvm/<vm-name>/<vm-image> <remote-server-ip>:/tmp/

On the remote server create a dir for the VM and copy it from /tmp to that dir:

mkdir /var/lib/kvm/<vm-name>
mv /tmp/<vm-image> /var/lib/kvm/<vm-name>/

Now you also need the xml file for that VM. Since it is just text you can copy it, create a file on remote server and paste it there. The xml file is found in this dir:

/etc/libvirt/qemu

After you copied the VM image and xml file you can define and start it:

virsh define /etc/libvirt/qemu/<vm-name>.xml
virsh start <vm-name>
virsh autostart <vm-name>

Rename a VM

Shutdown the VM, dump the xml file and edit it.

virsh shutdown oldname
virsh dumpxml oldname > /etc/libvirt/qemu/newname.xml
vi /etc/libvirt/qemu/newname.xml

In newname.xml change "<name>oldname</name>" to "<name>newname</name>" and "

" to "

". Undefine the VM and define the new one.

virsh undefine oldname
mv /var/lib/kvm/oldname /var/lib/kvm/newname
virsh define /etc/libvirt/qemu/newname.xml
virsh start newname

or use

# virsh domrename $OLD_NAME $NEW_NAME

ssh to VM and follow the steps from here: changing the hostname

steps from salt minion need to be followed as well : salt

Additional steps delete it from zabbix , rename on the wiki if applicable , CAS changes and url name

Resizing Memory With Script

VM_ID="my_vm_id"
NEW_AMOUNT="4000"

EDITOR='sed -i "s;[0-9]*</currentMemory>;$NEW_AMOUNT</currentMemory>;"' virsh edit $VM_ID
EDITOR='sed -i "s;[0-9]*</memory>;$NEW_AMOUNT</memory>;"' virsh edit $VM_ID

sudo virsh shutdown $VM_ID
sudo virsh start $VM_ID

Useful Tools

Install tools

apt-get -y install libguestfs-tools virt-top

"ls" List a directory in a virtual machine.

# virt-ls -l -d ubuntu /root 

"cat" Display content of a file in a virtual machine.

# virt-cat -d ubuntu /etc/network/interfaces 


Edit a file in a virtual machine.

# virt-edit -d ubuntu /etc/netplan/01-netcfg.yaml

Edit a file in a virtual machine image.

# virt-edit -a /path/to/image.qcow2 /home/user/.bash_history

Display disk usage in a virtual machine.

# virt-df -h -d ubuntu

Display partition table in a virtual machine (helps a lot when growing a windows VM disk)

#virt-filesystems -a vm-image.qcow2 -l

Name       Type        VFS   Label            Size         Parent
/dev/sda1  filesystem  ntfs  System Reserved  104857600    -
/dev/sda2  filesystem  ntfs  -                53030682624  -
/dev/sda3  filesystem  ntfs  -                548405248    -

Mount a disk of a virtual machine

# guestmount -d ubuntu -i /mnt 
# ll /mnt

Display the status of virtual machines

# virt-top

VM-disk deleted - resolution

Solution 1

# lsof | grep 101
...
kvm       3649       root   18u      REG              253,2 2147483648     524290  (deleted)/var/lib/vz/images/101/vm-101-disk-1.raw
...

Important is the pid (3649) and the filediscriptor (18) do an copy (before that, it's a good idea to stop important services with open files inside the VM, like databases)

cp /proc/3649/fd/18 /var/lib/vz/images/101/vm-101-disk-1.raw

Voila, the disk-file (of an open-VM!) is copied back.

Solution 2

To conver the image from raw to qcow2

qemu-img convert -p -f qcow2 -O raw /proc/2850/fd/19 vm-100-disk-1.raw

Test the copied file with an dummy-VM before shutdown the original VM!


List all the VMs with the autostart option activated

# sudo virsh list --autostart

Snapshoot operations

With virsh

Create snapshoot

virsh shutdown vm_name
virsh snapshot-create-as --domain vm_name --name "snapshot_name" --description "Snapshot"

Restore snapshoot

virsh snapshot-list --domain vm_name
virsh snapshot-revert --domain vm_name --snapshotname snapshot_name

Delete snapshoot

virsh snapshot-delete --domain vm_name --snapshotname snapshot_name_to_be_deleted

With qemu-img

This is helpful when the VM was migrated between hosts and snapshots definition was not copied/defined as well

List snapshots

qemu-img info vm-disk.qcow2

Delete snapshot

 qemu-img snapshot -d snapshot-name vm-disk.qcow2

Adding a disk to VM

On the host, create an image

qemu-img create -f qcow2 /path/to/image.qcow2 10G

Attach the disk to the VM (check before if vda is used; if yes use vdb, vdc, etc.). Make sure to provide the full path to the image.

virsh shutdown vm-name
virsh attach-disk vm-name --source /path/to/image.qcow2 vdb --driver qemu --subdriver qcow2 --targetbus virtio --persistent

Before starting the VM check that the disk attached as qcow2 and not another type like raw.

#virsh edit vm-name

<disk type='file' device='disk'>
   <driver name='qemu' type='qcow2'/>
   <source file='/var/lib/kvm/ourbus-nc/ourbus-ncstorage1.qcow2'/>
   <target dev='vda' bus='virtio'/>
   <address type='pci' domain='0x0000' bus='0x00' slot='0x05' function='0x0'/>
</disk>

If type is not qcow2 change it and start the VM.

virsh start vm-name

On the VM, check disk vda has been attached

# ls -l /dev/disk/by-path/
lrwxrwxrwx 1 root root  9 Oct 23 13:44 virtio-pci-0000:00:05.0 -> ../../vda

Create a partition with parted or other tool

parted /dev/vda

If parted throws a warning that the disk size is only a few KB, there is a problem with the disk. In this case go back and investigate, otherwise go ahead and create the partition.

Format it

mkfs.ext4 /dev/vda1

If the disk will be used for data storage then reduce the space reserved for root operations

tune2fs -m 1 /dev/vda1

Find the UUID of the partition (the groups of numbers/letters before the arrow -> )

#ls -l /dev/disk/by-uuid/
lrwxrwxrwx 1 root root 10 Oct 23 13:45 936de7fd-084f-4456-898f-483341df1cf1 -> ../../vda1

Mount the partition using the UUID

mount /dev/disk/by-uuid/youruuid /path/to/mymountpoint

Append a line to /etc/fstab so your mount can survive a reboot

UUID=youruuid       /path/to/mymountpoint ext4    defaults        0       0

Detach disk from a VM

virsh detach-disk vm-name vda --config

Converting

Info about image

qemu-img info image.vmdk 

From .vdi to .qcow2

qemu-img convert -f vdi -O qcow2 from.vdi to.qcow2

From qcow2 to .vdi

qemu-img convert -O vdi from.qcow2 to.vdi

From .img to .qcow2

qemu-img convert -f raw from.img -O qcow2 to.qcow2

From .qcow2 to .raw

qemu-img convert -O raw from.qcow2 to.raw

List OS suported variants bt virt-install

When creating a guest with virt-install you need to specify the --os-variant. To get a list of acceptable values (on Ubuntu 16.04), install the libosinfo-bin package before running the command below:

# osinfo-query os

Reset and set the root password of a certain VM

First shutdown the VM:

virsh shutdown <vm_name>

Secondly get the path of the image:

virsh dumpxml <vm_name> | grep 'source file'

Afterwards set the root password:

 virt-customize -a <path_of_image> --root-password password:NewRootUserPasswordHere --uninstall cloud-init


Enable Virsh Console Access For KVM Guests

In order to use VM console access (if it runs out of internet access, for example), the following commands must be run on each guest.

systemctl enable serial-getty@ttyS0.service
systemctl start serial-getty@ttyS0.service

After running the two commands we can easily connect from the main host using the command:

sudo virsh console --domain <vm_name>