File: image.py

package info (click to toggle)
virtnbdbackup 2.43-1
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 672 kB
  • sloc: python: 4,429; makefile: 9
file content (157 lines) | stat: -rw-r--r-- 5,264 bytes parent folder | download | duplicates (2)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#!/usr/bin/python3
"""
Copyright (C) 2023 Michael Ablassmeier <abi@grinser.de>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
"""
import os
import logging
import json
from argparse import Namespace
from typing import List, Dict
from libvirtnbdbackup.qemu import util as qemu
from libvirtnbdbackup import output
from libvirtnbdbackup import common as lib
from libvirtnbdbackup.exceptions import RestoreError
from libvirtnbdbackup.qemu.exceptions import ProcessError
from libvirtnbdbackup.output.exceptions import OutputException
from libvirtnbdbackup.ssh.exceptions import sshError


def getConfig(  # pylint: disable=too-many-statements
    args: Namespace, meta: Dict[str, str]
) -> List[str]:
    """Check if backup includes exported qcow config and return a list
    of options passed to qemu-img create command"""
    opt: List[str] = []
    qcowConfig = None
    qcowConfigFile = lib.getLatest(args.input, f"{meta['diskName']}*.qcow.json*", -1)
    if not qcowConfigFile:
        logging.warning(
            "No QCOW image config found in [%s], will use default options.", args.input
        )
        return opt

    lastConfigFile = qcowConfigFile[0]

    try:
        with output.openfile(lastConfigFile, "rb") as qFh:
            qcowConfig = json.loads(qFh.read().decode())
        logging.info("Using QCOW options from backup file: [%s]", lastConfigFile)
    except (
        OutputException,
        json.decoder.JSONDecodeError,
    ) as errmsg:
        logging.warning(
            "Unable to load original QCOW image config, using defaults: [%s].",
            errmsg,
        )
        return opt

    try:
        opt.append("-o")
        opt.append(f"compat={qcowConfig['format-specific']['data']['compat']}")
    except KeyError as errmsg:
        logging.warning("Unable apply QCOW specific compat option: [%s]", errmsg)

    try:
        opt.append("-o")
        opt.append(f"cluster_size={qcowConfig['cluster-size']}")
    except KeyError as errmsg:
        logging.warning("Unable apply QCOW specific cluster_size option: [%s]", errmsg)

    try:
        if qcowConfig["format-specific"]["data"]["lazy-refcounts"]:
            opt.append("-o")
            opt.append("lazy_refcounts=on")
    except KeyError as errmsg:
        logging.warning(
            "Unable apply QCOW specific lazy_refcounts option: [%s]", errmsg
        )

    try:
        cType = qcowConfig["format-specific"]["data"]["compression-type"]
        opt.append("-o")
        opt.append(f"compression_type={cType}")
        logging.info("Setting image compression type: [%s]", cType)
    except KeyError as errmsg:
        pass

    try:
        dataFile = qcowConfig["format-specific"]["data"]["data-file"]
        if args.adjust_config is True:
            dataFilePath = os.path.join(
                args.output,
                os.path.basename(dataFile),
            )
            logging.info(
                "QCOW image with data-file backend detected: [%s], adjusting path to: [%s]",
                dataFile,
                dataFilePath,
            )
        else:
            logging.info(
                "QCOW image with data-file backend detected, keeping original path: [%s]",
                dataFile,
            )

        opt.append("-o")
        opt.append(f"data_file={dataFilePath}")
    except KeyError as errmsg:
        pass

    try:
        if qcowConfig["format-specific"]["data"]["data-file-raw"] is True:
            opt.append("-o")
            opt.append("data_file_raw=true")
        logging.info("QCOW image with RAW data-file backend detected.")
    except KeyError as errmsg:
        pass

    return opt


def create(args: Namespace, meta: Dict[str, str], targetFile: str, sshClient):
    """Read QCOW image related backup json and create target image file using
    its original options"""
    options = getConfig(args, meta)
    logging.info(
        "Create virtual disk [%s] format: [%s] size: [%s] based on: [%s] preallocated: [%s]",
        targetFile,
        meta["diskFormat"],
        meta["virtualSize"],
        meta["checkpointName"],
        args.preallocate,
    )

    if lib.exists(args, targetFile):
        logging.error(
            "Target file already exists: [%s], won't overwrite.",
            os.path.abspath(targetFile),
        )
        raise RestoreError

    qFh = qemu.util(meta["diskName"])
    try:
        qFh.create(
            args,
            targetFile,
            int(meta["virtualSize"]),
            meta["diskFormat"],
            options,
            sshClient,
        )
    except (ProcessError, sshError) as e:
        logging.error("Failed to create restore target: [%s]", e)
        raise RestoreError from e