summaryrefslogtreecommitdiffstats
path: root/tools/nbdfuse.py
blob: 09591ea46540a31e18b04bddb8baec309ca607af (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import logging
import os
import tempfile

from subprocess import Popen, PIPE
from time import sleep
from . import log, rmdir

__all__ = ["mount"]

L = logging.getLogger(__name__)


@log
def mount(path):
    """Mount a disk image file as a RAW image file in the local filesystem with
    read-only support using `qemu-nbd` + `nbdfuse`.

    See also:
    https://manpages.debian.org/bullseye/qemu-utils/qemu-nbd.8.en.html
    https://manpages.debian.org/bullseye/libnbd-bin/nbdfuse.1.en.html

    Make sure you have the following packages installed:
        $ sudo apt install qemu-utils nbdfuse

    Args:
        path (str): Path to the disk image file.

    Returns:
        Path to the directory containing a single virtual file named `nbd`.
    """
    mp = tempfile.mkdtemp()
    cmd = [
        "nbdfuse",
        "--readonly",
        mp,
        "--socket-activation",
        "qemu-nbd",
        "--read-only",
        path
    ]

    try:
        p = Popen(cmd, stdout=PIPE, stderr=PIPE, text=True)
    except Exception as e:
        L.error("failed to execute command %s: %r", cmd, e)
        rmdir(mp)
        return ""

    while p.poll() is None:
        if os.path.ismount(mp):
            return mp
        sleep(1)

    ret = p.poll()
    out, err = p.communicate()
    out, err = out.strip(), err.strip()
    L.error("retcode: %d, stdout: %s, stderr: %s", ret, out, err)

    rmdir(mp)

    return ""