Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion upload-ami/default.nix
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ let
dependencies = map parseDependency pyproject.project.dependencies;
args =
(lib.genAttrs (
[ "buildPythonApplication" ] ++ (map ({ name, ... }: name) (requires ++ dependencies))
[
"buildPythonApplication"
"unittestCheckHook"
]
++ (map ({ name, ... }: name) (requires ++ dependencies))
))
(x: false);
in
Expand All @@ -48,6 +52,12 @@ let
pyproject = true;
nativeBuildInputs = lib.flatten (map resolvePkgs requires);
propagatedBuildInputs = lib.flatten (map resolvePkgs dependencies);
nativeCheckInputs = [ python3Packages.unittestCheckHook ];
unittestFlags = [
"-s"
"tests"
"-v"
];
passthru.upload-ami.pyproject = pyproject;
}
) args;
Expand Down
40 changes: 27 additions & 13 deletions upload-ami/src/upload_ami/upload_ami.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import hashlib
import logging
from pathlib import Path
from typing import Iterable, Literal, TypedDict
from typing import Iterable, Literal, NotRequired, TypedDict
import boto3
import boto3.ec2
import boto3.ec2.createtags
Expand All @@ -12,7 +12,11 @@

from mypy_boto3_ec2.client import EC2Client
from mypy_boto3_ec2.literals import BootModeValuesType
from mypy_boto3_ec2.type_defs import RegionTypeDef, RegisterImageRequestTypeDef
from mypy_boto3_ec2.type_defs import (
EbsBlockDeviceTypeDef,
RegionTypeDef,
RegisterImageRequestTypeDef,
)
from mypy_boto3_s3.client import S3Client

from concurrent.futures import ThreadPoolExecutor
Expand All @@ -25,7 +29,9 @@ class ImageInfo(TypedDict):
label: str
system: str
boot_mode: BootModeValuesType
format: str
format: NotRequired[str]
root_volume_size_gib: NotRequired[int]
tpm_support: NotRequired[bool]


def upload_to_s3_if_not_exists(
Expand Down Expand Up @@ -189,17 +195,22 @@ def register_image_if_not_exists(
else:
raise Exception("Unknown system: " + image_info["system"])

ebs: EbsBlockDeviceTypeDef = {"SnapshotId": snapshot_id, "VolumeType": "gp3"}
# Without VolumeSize, EC2 sizes the root volume to the snapshot.
if "root_volume_size_gib" in image_info:
snapshot = ec2.describe_snapshots(SnapshotIds=[snapshot_id])["Snapshots"][0]
ebs["VolumeSize"] = max(
image_info["root_volume_size_gib"], snapshot.get("VolumeSize", 0)
)

register_image_kwargs: RegisterImageRequestTypeDef = {
"Name": image_name,
"Architecture": architecture,
"BootMode": image_info["boot_mode"],
"BlockDeviceMappings": [
{
"DeviceName": "/dev/xvda",
"Ebs": {
"SnapshotId": snapshot_id,
"VolumeType": "gp3",
},
"Ebs": ebs,
}
],
"RootDeviceName": "/dev/xvda",
Expand All @@ -218,11 +229,10 @@ def register_image_if_not_exists(
],
}

if (
enable_tpm
and architecture == "x86_64"
and image_info["boot_mode"] == "uefi"
):
tpm_support = image_info.get(
"tpm_support", enable_tpm and image_info["boot_mode"] == "uefi"
)
if tpm_support:
register_image_kwargs["TpmSupport"] = "v2.0"

logging.info(f"Registering image {image_name} with snapshot {snapshot_id}")
Expand Down Expand Up @@ -379,6 +389,10 @@ def upload_ami(

image_format = image_info.get("format") or "VHD"
if ebs_direct:
# EBS direct uploads the file's bytes as the disk.
assert (
image_info.get("format", "RAW") == "RAW"
), "--ebs-direct needs a raw image"
snapshot_id = import_snapshot_ebs_direct(
ec2, image_name, image_file, ec2.meta.region_name
)
Expand Down Expand Up @@ -446,7 +460,7 @@ def main() -> None:
"--enable-tpm",
action="store_true",
default=False,
help="Enable TPM 2.0 support for UEFI x86_64 images",
help="Enable TPM 2.0 support for UEFI images whose image info has no tpm_support",
)

parser.add_argument(
Expand Down
113 changes: 113 additions & 0 deletions upload-ami/tests/test_upload_ami.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
import unittest
from pathlib import Path
from typing import Any, cast
from unittest.mock import MagicMock, patch

from upload_ami import upload_ami
from upload_ami.upload_ami import ImageInfo, register_image_if_not_exists


def image_info(**fields: Any) -> ImageInfo:
return cast(
ImageInfo,
{
"file": "/nix/store/image.vhd",
"label": "26.11",
"system": "x86_64-linux",
"boot_mode": "uefi",
**fields,
},
)


def fake_ec2(snapshot_gib: int = 3) -> MagicMock:
ec2 = MagicMock()
ec2.describe_images.return_value = {"Images": []}
ec2.describe_snapshots.return_value = {"Snapshots": [{"VolumeSize": snapshot_gib}]}
ec2.register_image.return_value = {"ImageId": "ami-1"}
return ec2


def register(
info: ImageInfo, snapshot_gib: int = 3, enable_tpm: bool = False
) -> dict[str, Any]:
ec2 = fake_ec2(snapshot_gib)
register_image_if_not_exists(ec2, "name", info, "snap-1", False, enable_tpm)
return cast(dict[str, Any], ec2.register_image.call_args.kwargs)


class RootVolumeSize(unittest.TestCase):
def test_absent(self) -> None:
ebs = register(image_info())["BlockDeviceMappings"][0]["Ebs"]
self.assertNotIn("VolumeSize", ebs)

def test_larger_than_snapshot(self) -> None:
ebs = register(image_info(root_volume_size_gib=4), snapshot_gib=3)[
"BlockDeviceMappings"
][0]["Ebs"]
self.assertEqual(ebs["VolumeSize"], 4)

def test_smaller_than_snapshot(self) -> None:
ebs = register(image_info(root_volume_size_gib=4), snapshot_gib=6)[
"BlockDeviceMappings"
][0]["Ebs"]
self.assertEqual(ebs["VolumeSize"], 6)


class TpmSupport(unittest.TestCase):
def test_absent_without_flag(self) -> None:
self.assertNotIn("TpmSupport", register(image_info()))

def test_absent_with_flag(self) -> None:
for system in ("x86_64-linux", "aarch64-linux"):
with self.subTest(system=system):
kwargs = register(image_info(system=system), enable_tpm=True)
self.assertEqual(kwargs["TpmSupport"], "v2.0")

def test_absent_with_flag_without_uefi(self) -> None:
info = image_info(boot_mode="uefi-preferred")
self.assertNotIn("TpmSupport", register(info, enable_tpm=True))

def test_true(self) -> None:
kwargs = register(image_info(tpm_support=True))
self.assertEqual(kwargs["TpmSupport"], "v2.0")

def test_false_overrides_flag(self) -> None:
kwargs = register(image_info(tpm_support=False), enable_tpm=True)
self.assertNotIn("TpmSupport", kwargs)


class Format(unittest.TestCase):
def upload(self, info: ImageInfo, ebs_direct: bool) -> MagicMock:
with (
patch("boto3.client", return_value=fake_ec2()),
patch.object(upload_ami, "import_snapshot_ebs_direct") as ebs,
patch.object(upload_ami, "import_snapshot_if_not_exist") as s3,
patch.object(upload_ami, "register_image_if_not_exists"),
):
upload_ami.upload_ami(
info, "bucket", False, "", "", False, [], False, "vmimport", ebs_direct
)
return ebs if ebs_direct else s3

def test_ebs_direct_absent(self) -> None:
self.upload(image_info(), ebs_direct=True).assert_called_once()

def test_ebs_direct_raw(self) -> None:
self.upload(image_info(format="RAW"), ebs_direct=True).assert_called_once()

def test_ebs_direct_refuses_vhd(self) -> None:
with self.assertRaises(AssertionError):
self.upload(image_info(format="VHD"), ebs_direct=True)

def test_s3_absent(self) -> None:
s3 = self.upload(image_info(), ebs_direct=False)
self.assertEqual(s3.call_args.args[5], "VHD")

def test_s3_raw(self) -> None:
s3 = self.upload(image_info(format="RAW"), ebs_direct=False)
self.assertEqual(s3.call_args.args[5], "RAW")


if __name__ == "__main__":
unittest.main()
Loading