Created
July 12, 2021 16:30
-
-
Save candlerb/757cbfc7a77a7e9449ba0f084818275d to your computer and use it in GitHub Desktop.
gf-run.py (create qcow2 clones and upload data to them)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python3 | |
import os | |
import shutil | |
import subprocess | |
import sys | |
index = int(sys.argv[1]) | |
num_disks = int(sys.argv[2]) | |
base = os.path.abspath("mybase.img") | |
os.environ["LIBGUESTFS_DEBUG"] = "1" | |
#os.environ["LIBGUESTFS_TRACE"] = "1" | |
tmp_dir = "/tmp/gf-run.%d" % os.getpid() | |
MAPPING = str.maketrans('0123456789','ABCDEFGHIJ') | |
if os.path.exists(tmp_dir): | |
shutil.rmtree(tmp_dir) | |
os.makedirs(tmp_dir) | |
configs = [] | |
for i in range(num_disks): | |
name = "node%d" % i | |
data1 = b"X" * 4000 | |
data1_f = os.path.join(tmp_dir, "%s.data1" % name) | |
with open(data1_f, "wb") as f: | |
f.write(data1) | |
data2 = b"Y" * (256*1024) | |
data2_f = os.path.join(tmp_dir, "%s.data2" % name) | |
with open(data2_f, "wb") as f: | |
f.write(data2) | |
uploads = { | |
"/data1": data1_f, | |
"/data2": data2_f, | |
} | |
label = ("%d" % i).translate(MAPPING) # can only contain a-zA-Z | |
part = 1 | |
configs.append((name, uploads, label, part)) | |
# Generate all qcow2 files | |
gfcmd = [ | |
"guestfish", "--", | |
] | |
for name, uploads, label, part in configs: | |
qcowfile = os.path.join(tmp_dir, "%s.qcow2" % name) | |
if not os.path.exists(base): | |
raise RuntimeError("No such backing file: %s" % image) | |
gfcmd.extend([ | |
"disk-create", qcowfile, "qcow2", "-1", "backingfile:%s" % base, "compat:1.1", ":", | |
"add", qcowfile, "label:%s" % label, ":", | |
]) | |
gfcmd.extend([ | |
"run", ":", | |
]) | |
for name, uploads, label, part in configs: | |
gfcmd.extend(["mount", "/dev/disk/guestfs/%s%d" % (label, part), "/", ":"]) | |
for dst, src in uploads.items(): | |
gfcmd.extend(["upload", src, dst, ":"]) | |
gfcmd.extend(["umount", "/", ":"]) | |
res = subprocess.run(gfcmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
if res.returncode: | |
err_f = os.path.join(tmp_dir, "err") | |
with open(err_f, "wb") as f: | |
f.write(res.stdout) | |
raise RuntimeError("guestfish(%d) exited with code %d" % (index, res.returncode)) | |
# No failure, tidy up | |
shutil.rmtree(tmp_dir) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment