osbuild-mpp: conditional losetup

`mpp-define-images` can create an image file, using `losetup` to deal
with non-standard sector sizes requires root. Not all users run
`osbuild-mpp` as root.

While I am not a fan of "suddenly sudo" based on the input manifest this
does alleviate builds breaking for manifests with default sector sizes
when non-root.
This commit is contained in:
Simon de Vlieger 2023-11-30 11:40:20 +01:00
parent 0a2e0bb3d2
commit b225d1cf04

View file

@ -968,6 +968,8 @@ class PartitionTable:
class Image: class Image:
DEFAULT_SECTOR_SIZE = 512
def __init__(self, size, layout): def __init__(self, size, layout):
self.size = size self.size = size
self.layout = layout self.layout = layout
@ -976,19 +978,27 @@ class Image:
def from_dict(cls, js): def from_dict(cls, js):
size = js["size"] size = js["size"]
data = js["table"] data = js["table"]
sector_size = js.get('sector_size', 512) sector_size = js.get('sector_size', Image.DEFAULT_SECTOR_SIZE)
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
image = os.path.join(tmp, "disk.img") image = os.path.join(tmp, "disk.img")
subprocess.run(["truncate", "--size", size, image], check=True) subprocess.run(["truncate", "--size", size, image], check=True)
cp = subprocess.run(["losetup", "--find", "--show", f"--sector-size={sector_size}", image],
stdout=subprocess.PIPE, check=True) table = PartitionTable.from_dict(data)
loopimage = cp.stdout.rstrip()
try: # Running losetup requires to be root but losetup is only necessary if the sector size
table = PartitionTable.from_dict(data) # is different from the default.
table.write_to(loopimage) if sector_size == Image.DEFAULT_SECTOR_SIZE:
finally: table.write_to(image)
subprocess.run(["losetup", "-d", loopimage]) else:
cp = subprocess.run(["losetup", "--find", "--show", f"--sector-size={sector_size}", image],
stdout=subprocess.PIPE, check=True)
loopimage = cp.stdout.rstrip()
try:
table.write_to(loopimage)
finally:
subprocess.run(["losetup", "-d", loopimage])
return cls(size, table) return cls(size, table)