QCOW2 unusual recovery

2 min read
QCOW2 unusual recovery

How i recover damaged qcow2

Working with qcow2 images is a common task in virtualization environments, but sometimes these images can become damaged or corrupted. In this post, I’ll share my experience on how I successfully recovered a damaged qcow2 image using qemu-nbd and ddrescure.

The problem

Many times occurred when I was working with qcow2 images, I found myself in a situation where the image was damaged and I couldn’t access the data inside. This can happen due to various reasons such as power failure, hardware issues, or software bugs.

In this situation, i was unable to recreate the image from a backup, so I had to find a way to recover the data from the damaged image.

How to take it home

First, is obvious to use the integrated check command of qemu-img to check and try to correct the image:

qemu-img check -r all /path/to/damaged.qcow2

Most of the time, this command can fix minor issues with the qcow2 image, but in my case, it was not able to recover the data. So I had to look for an alternative solution. I tried using qemu-nbd to connect the damaged qcow2 image as a network block device, and then I used ddrescue to copy the data from the damaged image to a new one.

modprobe nbd max_part=8

qemu-nbd --connect=/dev/nbd0 -r /path/to/damaged.qcow2
ddrescue -f -n /dev/nbd0 /path/to/recovered.raw /path/to/mapfile.map
qemu-nbd --disconnect /dev/nbd0

qemu-img convert -O qcow2 /path/to/recovered.raw /path/to/recovered.qcow2

why the map file?

ddrescue uses a map file to keep track of which parts of the source have been successfully copied and which parts are still pending. This allows you to resume the recovery process if it gets interrupted, without losing progress. You can resume the recovery with:

ddrescue -f -n /dev/nbd0 /path/to/recovered.raw /path/to/mapfile.map

if the mapfile show lots of error or bad sectors, it means that the damage is severe and the chances of recovering the data are low. The last resort in this case is to use ddrescue with the -r 10and-d to retry harder on the bad sectors, but this can take a long time and may not always be successful.

ddrescue -f -d -r 10 /dev/nbd0 /path/to/recovered.raw /path/to/mapfile.map

At the next boot (if the vm boots up), you should be able to access the data and run fsck to check and fix any residual filesystem issues.

About the Author

Filippo Ferrando
Cyber Security Student

Filippo Ferrando is a graduate in Computer Science with extensive knowledge of Linux systems and Python programming.

He currently works at Elemento Cloud to innovate in the world of cloud computing.