Skip to content
Open
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
44 changes: 44 additions & 0 deletions .github/workflows/validate_images.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
name: Validate Image Offerings

on:
schedule:
- cron: "0 6 * * 1"
workflow_dispatch:

jobs:
validate-images:
runs-on: ubuntu-24.04

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's add a conditional that prevents this workflow from running on any forked remotes. Limit it to run on canonical/pycloudlib repo (like we do in cloud-init scheduled workflows)

steps:
- name: Install dependencies
run: |
sudo apt-get update -q
sudo apt-get install -qy distro-info
sudo snap install lxd

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think setup-lxd action does this.

- name: Git checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install uv
uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
- name: Setup LXD
uses: canonical/setup-lxd@8c6a87bfb56aa48f3fb9b830baa18562d8bfd4ee # v1
- name: Setup pycloudlib config and ssh key
env:
GCE_CREDENTIALS_JSON: ${{ secrets.GCE_CREDENTIALS_JSON }}
PYCLOUDLIB_TOML: ${{ secrets.PYCLOUDLIB_TOML }}
run: |
ssh-keygen -P "" -q -f ~/.ssh/id_rsa
mkdir -p ~/.config
if [ -n "$GCE_CREDENTIALS_JSON" ]; then
echo "$GCE_CREDENTIALS_JSON" > ~/.config/gce_credentials
fi
if [ -n "$PYCLOUDLIB_TOML" ]; then
echo "$PYCLOUDLIB_TOML" > ~/.config/pycloudlib.toml
fi
if ! grep -q '^\[lxd\]' ~/.config/pycloudlib.toml 2>/dev/null; then
echo "[lxd]" >> ~/.config/pycloudlib.toml
fi

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than trying to fix an incorrect/empty PYCOUDLIB_TOML. Let's make this PYCOUDLIB_TOML secret required (like we do in cloud-init github workflows). Then we can have a clear error when the repo doesn't contain such a secret.

- name: Run release metadata and image offering validation
run: |
GOOGLE_APPLICATION_CREDENTIALS=~/.config/gce_credentials \
uvx --with tox-uv tox -e integration-tests -- --color=yes \
tests/integration_tests/test_ubuntu_release_metadata.py \
tests/integration_tests/test_image_offerings.py
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1!12.0.0
1!12.1.0
2 changes: 1 addition & 1 deletion pycloudlib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
"xenial": "16.04",
}

LTS_RELEASES = ["xenial", "bionic", "focal", "jammy", "noble"]
LTS_RELEASES = ["bionic", "focal", "jammy", "noble", "resolute"]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's separate ESM_LTS_RELEASES from STANDARD_SUPPORT_LTS_RELEASES in this file instead of dropping "xenial" altogether. This will allow consumers to differentiate Pro-supported (ESM releases) from standard support releases in one place. I don't like that we are adding a separate set of lists to maintain in test_image_offerings as we now have two separate locations to updated release names instead of one. Please move related ACTIVE_RELEASES and STANDARD_LTS_RELEASES out of that unittest. Rename as you see fit.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You've also made a good point that Xenial is actualy out of ESM now, so dropping it is reasonable. I still think differentiating ESM_LTS_RELEASES from LTS_RELEASES is a reasonable approach to help test lookups for PRO supported images (esm) vs standard support.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we are dropping xenial test support from pycloudlib, let's make it official and drop support everywhere (ec2/azure/gce etc) and create a separate commit for it.


log = logging.getLogger(__name__)

Expand Down
211 changes: 211 additions & 0 deletions tests/integration_tests/test_image_offerings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,211 @@
"""Integration tests validating daily_image and released_image offerings per cloud."""

from __future__ import annotations

import shutil
import subprocess
from contextlib import contextmanager
from typing import Iterator

import pytest
import requests
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError
from botocore.exceptions import BotoCoreError
from google.auth.exceptions import GoogleAuthError
from ibm_cloud_sdk_core import ApiException
from oci.exceptions import ConfigFileNotFound, InvalidConfig, ProfileNotFound

import pycloudlib
from pycloudlib.azure.cloud import (
UBUNTU_DAILY_IMAGES,
UBUNTU_DAILY_PRO_FIPS_IMAGES,
UBUNTU_DAILY_PRO_FIPS_UPDATES_IMAGES,
UBUNTU_DAILY_PRO_IMAGES,
UBUNTU_RELEASE_IMAGES,
)
from pycloudlib.azure.util import parse_image_id
from pycloudlib.cloud import BaseCloud, ImageType
from pycloudlib.errors import CloudSetupError, MissingPrerequisiteError
from pycloudlib.ibm_classic.errors import IBMClassicException
from pycloudlib.util import UBUNTU_RELEASE_VERSION_MAP
from pycloudlib.vmware.cloud import SERIES_TO_TEMPLATE

_SETUP_ERRORS = (
ApiException,
BotoCoreError,
ClientAuthenticationError,
CloudSetupError,
ConfigFileNotFound,
FileNotFoundError,
GoogleAuthError,
IBMClassicException,
InvalidConfig,
KeyError,
MissingPrerequisiteError,
ProfileNotFound,
RuntimeError,
ValueError,
)
Comment on lines +33 to +48

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We are generally skipping on any error whatsoever, which feels a bit like we are likely of overlook true runtime errors, valueerrors and keywerrors that represent mis-configuration. Can we dial this list down a bit to specific failures we are trying to avoid? I think only absence of configuration for the platform in pycloudlib.toml should be a valid condition. The rest of these excceptions feel like they are ignoring mis-configured or partially configured environments.


ACTIVE_RELEASES = ["bionic", "focal", "jammy", "noble", "resolute", "stonking"]
STANDARD_LTS_RELEASES = ["jammy", "noble", "resolute"]


@contextmanager
def _cloud_or_skip(cloud_cls: type[BaseCloud]) -> Iterator[BaseCloud]:
"""Instantiate cloud_cls or skip the test if credentials/prerequisites are absent."""
try:

@blackboxsw blackboxsw Dec 2, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be worth first checking if the cloud platform type [qemu] [lxd] [ec2] etc is defined in pycloudlib.toml and skip if unconfigured to avoid trying to catch all the other exceptions and instead provide a clear skip messages about missing config.

cloud = cloud_cls(tag="pycl-img-check", timestamp_suffix=True)
except _SETUP_ERRORS as exc:
pytest.skip(f"Skipping {cloud_cls.__name__}: {exc}")
with cloud:
yield cloud


@pytest.mark.ci
@pytest.mark.main_check
def test_azure_image_offerings():
"""Verify Azure daily and release image URNs resolve to non-deprecated Marketplace offerings."""
with _cloud_or_skip(pycloudlib.Azure) as cloud:
daily_maps = {
ImageType.GENERIC: UBUNTU_DAILY_IMAGES,
ImageType.PRO: UBUNTU_DAILY_PRO_IMAGES,
ImageType.PRO_FIPS: UBUNTU_DAILY_PRO_FIPS_IMAGES,
ImageType.PRO_FIPS_UPDATES: UBUNTU_DAILY_PRO_FIPS_UPDATES_IMAGES,
}
checks = [
(image_type, release, cloud.daily_image(release, image_type=image_type))
for image_type, image_map in daily_maps.items()
for release in image_map
]
checks.extend(
(ImageType.GENERIC, release, cloud.released_image(release))
for release in UBUNTU_RELEASE_IMAGES
)

for image_type, release, urn in checks:
parsed = parse_image_id(urn)
assert parsed, f"Invalid Azure URN for {release} ({image_type.name}): {urn}"
try:
versions = cloud.compute_client.virtual_machine_images.list(
location=cloud.location,
publisher_name=parsed["publisher"],
offer=parsed["offer"],
skus=parsed["sku"],
top=1,
)
assert versions, f"No Azure offering for {release} ({image_type.name}): {urn}"
version = (
versions[-1].name
if parsed.get("version") in (None, "latest")
else parsed["version"]
)
img = cloud.compute_client.virtual_machine_images.get(
location=cloud.location,
publisher_name=parsed["publisher"],
offer=parsed["offer"],
skus=parsed["sku"],
version=version,
)
except HttpResponseError as exc:
pytest.fail(f"Unresolvable Azure URN {urn} ({release}, {image_type.name}): {exc}")

dep = getattr(img, "image_deprecation_status", None)
assert not (
dep and dep.image_state == "Deprecated"
), f"Deprecated Azure URN {urn} ({release}, {image_type.name})"


@pytest.mark.ci

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we want this run on every PR? I think we can limit this to running on main_check once a merge happens. I don't want to block on every PR due to image offering changes.

@pytest.mark.main_check
def test_ec2_image_offerings():
"""Verify EC2 daily_image and released_image resolve for supported image types."""
matrix = {
ImageType.GENERIC: [*STANDARD_LTS_RELEASES, "stonking"],

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rather than hard-coding "stonking" should we instead find a way to sort UBUNTU_RELEASE_VERSION_MAP based on XX.YY value and include every interim release name > LTS_RELEASES[-1]?

ImageType.PRO: ["bionic", "focal", *STANDARD_LTS_RELEASES],
ImageType.PRO_FIPS: ["bionic", "focal"],
ImageType.PRO_FIPS_UPDATES: ["focal", "jammy"],
}
with _cloud_or_skip(pycloudlib.EC2) as cloud:
for image_type, releases in matrix.items():
for release in releases:
assert cloud.daily_image(release, image_type=image_type).startswith("ami-")
assert cloud.released_image(release, image_type=image_type).startswith("ami-")


@pytest.mark.ci
@pytest.mark.main_check
def test_gce_image_offerings():
"""Verify GCE daily_image and released_image resolve to non-deprecated images."""
matrix = {
ImageType.GENERIC: [*STANDARD_LTS_RELEASES, "stonking"],
ImageType.PRO: ["focal", "jammy", "noble"],
ImageType.PRO_FIPS: ["focal"],
ImageType.PRO_FIPS_UPDATES: ["jammy"],
}
with _cloud_or_skip(pycloudlib.GCE) as cloud:
for image_type, releases in matrix.items():
for release in releases:
for image_path in (
cloud.daily_image(release, image_type=image_type),
cloud.released_image(release, image_type=image_type),
):
_, project, _, _, image_id = image_path.split("/")
img = cloud._images_client.get(project=project, image=image_id)
state = getattr(getattr(img, "deprecated", None), "state", "")
assert state not in (
"DEPRECATED",
"OBSOLETE",
"DELETED",
), f"Deprecated GCE image for {release} ({image_type.name}): {image_path}"


@pytest.mark.ci
@pytest.mark.main_check
@pytest.mark.parametrize("cloud_cls", [pycloudlib.LXDContainer, pycloudlib.LXDVirtualMachine])
def test_lxd_image_offerings(cloud_cls: type[BaseCloud]):
"""Verify LXD daily_image and released_image resolve for active Ubuntu releases."""
if not shutil.which("lxc"):
pytest.skip("Skipping LXD: 'lxc' CLI not installed")
with _cloud_or_skip(cloud_cls) as cloud:
for release in ACTIVE_RELEASES:
for image_type in (ImageType.GENERIC, ImageType.MINIMAL):
assert cloud.daily_image(release, image_type=image_type)
assert cloud.released_image(release, image_type=image_type)


@pytest.mark.ci
@pytest.mark.main_check
@pytest.mark.parametrize("cloud_cls", [pycloudlib.IBM, pycloudlib.IBMClassic, pycloudlib.OCI])
def test_generic_cloud_image_offerings(cloud_cls: type[BaseCloud]):
"""Verify IBM, IBMClassic, and OCI daily_image and released_image resolve."""
with _cloud_or_skip(cloud_cls) as cloud:
for release in STANDARD_LTS_RELEASES:
assert cloud.daily_image(release)
assert cloud.released_image(release)


@pytest.mark.ci
@pytest.mark.main_check
def test_qemu_image_offerings():
"""Verify QEMU cloud-image URLs exist for active Ubuntu releases."""
with _cloud_or_skip(pycloudlib.Qemu):
for release in ACTIVE_RELEASES:
ver = UBUNTU_RELEASE_VERSION_MAP[release]
urls = (
f"https://cloud-images.ubuntu.com/{release}/current/{release}-server-cloudimg-amd64.img",
f"https://cloud-images.ubuntu.com/releases/{release}/release/ubuntu-{ver}-server-cloudimg-amd64.img",
)
for url in urls:
resp = requests.head(url, allow_redirects=True, timeout=10)
assert resp.ok, f"Unavailable QEMU image URL {url}: HTTP {resp.status_code}"


@pytest.mark.ci
@pytest.mark.main_check
def test_vmware_image_offerings():
"""Verify VMWare template names resolve in vSphere."""
with _cloud_or_skip(pycloudlib.VMWare) as cloud:
for release in SERIES_TO_TEMPLATE:
for template in (cloud.daily_image(release), cloud.released_image(release)):
subprocess.run(["govc", "vm.info", template], env=cloud.env, check=True)
79 changes: 79 additions & 0 deletions tests/integration_tests/test_ubuntu_release_metadata.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""Integration tests validating Ubuntu release metadata in pycloudlib.util."""

from __future__ import annotations

import csv
import datetime
import io
import urllib.request
from pathlib import Path

import pytest

from pycloudlib.util import LTS_RELEASES, UBUNTU_RELEASE_VERSION_MAP

DISTRO_INFO_CSV = Path("/usr/share/distro-info/ubuntu.csv")
DISTRO_INFO_URL = "https://git.launchpad.net/ubuntu/+source/distro-info-data/plain/ubuntu.csv"


def _load_ubuntu_csv() -> list[dict[str, str]]:
"""Load Ubuntu release support matrix from upstream or local distro-info CSV."""
try:
with urllib.request.urlopen(DISTRO_INFO_URL, timeout=10) as resp:
return list(csv.DictReader(io.StringIO(resp.read().decode("utf-8"))))
except OSError:
if DISTRO_INFO_CSV.exists():
with DISTRO_INFO_CSV.open(encoding="utf-8") as fh:
return list(csv.DictReader(fh))
pytest.skip("Unable to load Ubuntu distro-info support matrix")


def _active_releases() -> tuple[dict[str, str], list[str], dict[str, str]]:
"""Return (active_version_map, active_lts_list, all_version_map) as of today."""
today = datetime.date.today().isoformat()
active_map: dict[str, str] = {}
active_lts: list[str] = []
all_map: dict[str, str] = {}

for row in _load_ubuntu_csv():
series = row["series"]
version = row["version"].split()[0]
all_map[series] = version

release_date = row.get("release") or ""
eol = row.get("eol-server") or row.get("eol") or ""
eol_esm = row.get("eol-esm") or ""
is_released = bool(release_date and release_date <= today)
is_active = bool((eol and eol > today) or (eol_esm and eol_esm > today))

if is_released and is_active:
active_map[series] = version
if "LTS" in row["version"]:
active_lts.append(series)

return active_map, active_lts, all_map


@pytest.mark.ci

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same with this test and others. Let's not block all PRs due to image changes, but rely on main_check runs to alert us side-channel to image/platform inconsistencies.

@pytest.mark.main_check
def test_ubuntu_release_version_map_up_to_date():
"""Verify UBUNTU_RELEASE_VERSION_MAP covers all active Ubuntu releases accurately."""
active_map, _, all_map = _active_releases()

missing = {k: v for k, v in active_map.items() if UBUNTU_RELEASE_VERSION_MAP.get(k) != v}
assert (
not missing
), f"UBUNTU_RELEASE_VERSION_MAP missing or mismatched active releases: {missing}"

mismatched = {
k: (v, all_map.get(k)) for k, v in UBUNTU_RELEASE_VERSION_MAP.items() if all_map.get(k) != v
}
assert not mismatched, f"UBUNTU_RELEASE_VERSION_MAP has invalid versions: {mismatched}"


@pytest.mark.ci
@pytest.mark.main_check
def test_lts_releases_active_support():
"""Verify LTS_RELEASES matches the currently active Ubuntu LTS releases."""
_, active_lts, _ = _active_releases()
assert LTS_RELEASES == active_lts