diff --git a/README.md b/README.md index 44d0810..beabfb7 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ reach more than one. | `list_locations()` | Cities where servers are sold. The ID is `Country/City`, such as `United States/Ashburn` | | `list_sizes(location=None)` | Plans, by plan code (`SC-GC-1C-1G-20`). vCPU, memory and disk are read from the code | | `list_images()` | Operating systems: `ubuntu_24_04`, `debian_13`, `rocky_9`... | -| `create_node(name, size, image, location, auth=...)` | Orders the cheapest matching offer and waits for an address | +| `create_node(name, size, image, location, auth=...)` | Orders the cheapest matching offer, or one from the provider you name, and waits for an address | | `list_nodes()`, `ex_get_node(id_or_hostname)` | Servers, with state, IPs and `extra` (plan, distro, tags, firewall, provider, city) | | `reboot_node`, `start_node`, `stop_node` | Power operations; each waits until it is done | | `destroy_node(node)` | Deletes the server | @@ -82,10 +82,15 @@ reach more than one. | `ex_firewall_ruleset` | Name or ID of a firewall ruleset to attach | | `ex_billing_type` | `usage` (hourly, default), `subscription` or `free` | | `ex_sort` | `price` (cheapest, default) or `rating` (best rated) | -| `ex_provider_id` | Only consider offers from this provider | +| `ex_provider` | Only order from this provider: its provider ID, its storefront slug (such as `acme-hosting`) or its name (`Acme Hosting`, any case) | +| `ex_provider_id` | Only consider offers from this provider ID; takes precedence over `ex_provider` | | `ex_plan_id`, `ex_region_id` | An exact plan and region, instead of size and location | | `ex_wait` | Wait until the server is provisioned and has an address (default `True`) | +Without `ex_provider` the cheapest offer wins (compute price, then rating), so the provider +can change between servers. Set `ex_provider` to keep it fixed. A name that more than one +provider uses raises `LibcloudError`; give the ID or storefront slug then. + Orders carry an idempotency key, so a lost response is retried without ordering a second server. Extra methods: `ex_set_tags(node, tags)`, `ex_attach_firewall(node, ruleset)` and `ex_detach_firewall(node)`. diff --git a/src/libcloud_noderings/_api/client.py b/src/libcloud_noderings/_api/client.py index 4bd15ba..a6fa697 100644 --- a/src/libcloud_noderings/_api/client.py +++ b/src/libcloud_noderings/_api/client.py @@ -514,6 +514,9 @@ def list_providers(self, plan_code, country, city, billing_type=None, ipv6_only= query["filterIpv6AvailableOnly"] = "true" return self.get("/v1/marketplace/providers", query).get("providers") or [] + def get_public_storefront(self, slug): + return self.get(f"/v1/public/storefronts/{path_escape(slug)}").get("storefront") + def get_provider(self, provider_id): return self.get(f"/v1/marketplace/providers/{path_escape(provider_id)}").get("provider") diff --git a/src/libcloud_noderings/_api/compute.py b/src/libcloud_noderings/_api/compute.py index dd66a68..4e5cac2 100644 --- a/src/libcloud_noderings/_api/compute.py +++ b/src/libcloud_noderings/_api/compute.py @@ -14,6 +14,7 @@ from libcloud_noderings._api.client import new_uuid from libcloud_noderings._api.client import snake from libcloud_noderings._api.client import trim_enum +from libcloud_noderings._api.marketplace import NoOfferError from libcloud_noderings._api.marketplace import find_offers from libcloud_noderings._api.marketplace import no_offer_message from libcloud_noderings._api.marketplace import offer_view @@ -104,21 +105,30 @@ def choose_offer( require_capabilities=None, require_ipv6=False, sort="price", + provider=None, ): - """Return ``(plan_id, region_id, offer)`` for the best matching offer.""" - offers, located = find_offers( - client, - plan_code, - country, - city, - billing_type=billing_type, - provider_id=provider_id, - require_capabilities=require_capabilities or [], - require_ipv6=require_ipv6, - sort=sort, - ) + """Return ``(plan_id, region_id, offer)`` for the best matching offer. + + ``provider`` limits the offers to one provider, given by ID, storefront slug or name.""" + try: + offers, located = find_offers( + client, + plan_code, + country, + city, + billing_type=billing_type, + provider_id=provider_id, + require_capabilities=require_capabilities or [], + require_ipv6=require_ipv6, + sort=sort, + provider=provider, + ) + except NoOfferError as exc: + raise NodeRingsUsageError(str(exc)) from exc if not offers: - raise NodeRingsUsageError(no_offer_message(plan_code, country, city, billing_type, located)) + raise NodeRingsUsageError( + no_offer_message(plan_code, country, city, billing_type, located, provider or provider_id) + ) best = offers[0] return best["plan_id"], best["region_id"], offer_view(best) diff --git a/src/libcloud_noderings/_api/marketplace.py b/src/libcloud_noderings/_api/marketplace.py index ba3dcfc..3292a3c 100644 --- a/src/libcloud_noderings/_api/marketplace.py +++ b/src/libcloud_noderings/_api/marketplace.py @@ -2,6 +2,11 @@ Marketplace offer lookup: turn a plan code and a city into a plan and region ID. """ +import re + +from libcloud_noderings._api.client import NodeRingsError +from libcloud_noderings._api.client import is_not_found +from libcloud_noderings._api.client import is_uuid from libcloud_noderings._api.client import trim_enum BILLING_TYPES = { @@ -16,6 +21,32 @@ class NoOfferError(Exception): pass +_SLUG_RE = re.compile(r"^[a-z0-9-]{1,80}$") + + +def resolve_provider(client, provider): + """Turn a provider ID, storefront slug or provider name into ``(provider_id, name)``. + + An ID or a slug that names a public storefront gives the provider ID. Anything + else is a provider name, matched without regard to case against the offers. + """ + value = (provider or "").strip() + if not value: + return None, None + if is_uuid(value): + return value, None + if _SLUG_RE.match(value): + try: + sf = client.get_public_storefront(value) + except NodeRingsError as exc: + if not is_not_found(exc): + raise + sf = None + if sf and sf.get("providerId"): + return sf["providerId"], None + return None, value + + def _amount(p): try: return float(p.get("unitAmount")) @@ -72,9 +103,16 @@ def find_offers( require_capabilities=None, require_ipv6=False, sort="price", + provider=None, ): """Return (offers, located) where offers are sorted best first and located - counts the offers that matched the location before capability/IPv6 filters.""" + counts the offers that matched the location before capability/IPv6 filters. + + ``provider`` is a provider ID, storefront slug or provider name; see + :func:`resolve_provider`.""" + provider_name = None + if provider and not (provider_id or storefront_slug): + provider_id, provider_name = resolve_provider(client, provider) billing = BILLING_TYPES.get(billing_type or "", "") asset = ASSET_TYPES.get(asset_type or "virtual_machine", "ASSET_TYPE_VM") if storefront_slug: @@ -135,6 +173,15 @@ def find_offers( "prices": p.get("planPrices") or [], } ) + if provider_name: + want = provider_name.lower() + found = [o for o in found if (o["provider_name"] or "").strip().lower() == want] + ids = {o["provider_id"] for o in found} + if len(ids) > 1: + raise NoOfferError( + f"more than one provider is named {provider_name}; give its provider ID or " + "storefront slug instead" + ) located = len(found) need = set(require_capabilities or []) out = [ @@ -169,8 +216,10 @@ def offer_view(o): } -def no_offer_message(plan_code, country, city, billing_type, located): +def no_offer_message(plan_code, country, city, billing_type, located, provider=None): msg = f"No offer for plan code {plan_code} in {city}, {country}" + if provider: + msg += f" from provider {provider}" if billing_type: msg += f" with billing type {billing_type}" msg += "." diff --git a/src/libcloud_noderings/compute.py b/src/libcloud_noderings/compute.py index ef45001..2592f33 100644 --- a/src/libcloud_noderings/compute.py +++ b/src/libcloud_noderings/compute.py @@ -198,6 +198,7 @@ def create_node( ex_billing_type="usage", ex_sort="price", ex_provider_id=None, + ex_provider=None, ex_plan_id=None, ex_region_id=None, ex_wait=True, @@ -217,7 +218,11 @@ def create_node( :param ex_firewall_ruleset: name or ID of a firewall ruleset to attach :param ex_billing_type: ``usage`` (hourly, default), ``subscription`` or ``free`` :param ex_sort: ``price`` (cheapest, default) or ``rating`` (best rated) - :param ex_provider_id: only consider offers from this provider + :param ex_provider_id: only consider offers from this provider ID; takes precedence + over ``ex_provider`` + :param ex_provider: only consider offers from this provider, given by its ID, its + storefront slug (such as ``acme-hosting``) or its name (``Acme Hosting``, any + case); a name that more than one provider uses raises an error :param ex_plan_id: exact plan ID, instead of size and location :param ex_region_id: exact region ID, with ``ex_plan_id`` :param ex_wait: wait until the server is provisioned and has an address (default True) @@ -241,6 +246,7 @@ def create_node( billing_type=ex_billing_type, provider_id=ex_provider_id, sort=ex_sort, + provider=ex_provider, ) distro = image.id if isinstance(image, NodeImage) else str(image) diff --git a/tests/fakeapi.py b/tests/fakeapi.py index 854b59e..d233bc2 100644 --- a/tests/fakeapi.py +++ b/tests/fakeapi.py @@ -15,6 +15,18 @@ PLAN_ID = "11111111-1111-1111-1111-111111111111" REGION_ID = "22222222-2222-2222-2222-222222222222" +ACME_ID = "33333333-3333-3333-3333-333333333333" +ACME_PLAN_ID = "44444444-4444-4444-4444-444444444444" +ACME_REGION_ID = "55555555-5555-5555-5555-555555555555" +ACME_OFFER = { + "organizationId": ACME_ID, + "organizationName": "Acme Hosting", + "planId": ACME_PLAN_ID, + "planRegions": [{"country": "United States", "city": "Ashburn", "regionId": ACME_REGION_ID}], + "capabilities": ["guest_firewall"], + "rating": 4.8, + "planPrices": [{"unitAmount": "0.012", "unitName": "per compute-hour"}], +} class FakeResponse: @@ -40,6 +52,7 @@ class FakeNodeRings: # pylint: disable=too-many-public-methods def __init__(self): self.calls = [] + self.extra_providers = [] self.ssh_keys = {} self.zones = {} self.records = {} # zone_id -> {(name, type): {"ttl", "rdata"}} @@ -72,6 +85,8 @@ def __init__(self): ("DELETE", r"/v1/firewall/rules/([^/]+)", self.delete_rule), ("POST", r"/v1/firewall/rules/([^/]+)/move", self.move_rule), ("GET", r"/v1/marketplace/providers", self.list_providers), + ("GET", r"/v1/marketplace/providers/([^/]+)", self.get_provider), + ("GET", r"/v1/public/storefronts/([^/]+)", self.get_storefront), ("GET", r"/v1/marketplace/plans/([^/]+)", self.get_plan), ("GET", r"/v1/marketplace/plans", self.list_plans), ("GET", r"/v1/marketplace/regions", self.list_regions), @@ -142,10 +157,46 @@ def list_providers(self, q, b): # pylint: disable=unused-argument ], "capabilities": ["guest_firewall"], "planPrices": [{"unitAmount": "0.007", "unitName": "per compute-hour"}], - } + }, + ACME_OFFER, ] + + self.extra_providers } + def get_provider(self, q, b, provider_id): # pylint: disable=unused-argument + if provider_id != ACME_ID: + return _err(404, 5, "provider not found") + return 200, { + "provider": { + "provider": { + "organizationId": ACME_ID, + "organizationName": "Acme Hosting", + "rating": 4.8, + }, + "availablePlans": [ + { + "planId": ACME_PLAN_ID, + "planCode": "SC-GC-1C-1G-20", + "billingType": "BILLING_TYPE_USAGE", + "assetType": "ASSET_TYPE_VM", + "regions": [ + { + "country": "United States", + "city": "Ashburn", + "regionId": ACME_REGION_ID, + } + ], + "planPrices": ACME_OFFER["planPrices"], + } + ], + } + } + + def get_storefront(self, q, b, slug): # pylint: disable=unused-argument + if slug != "acme-hosting": + return _err(404, 5, "storefront not found") + return 200, {"storefront": {"slug": slug, "providerId": ACME_ID}} + # -- SSH keys ---------------------------------------------------------------- def list_keys(self, q, b): # pylint: disable=unused-argument diff --git a/tests/test_compute.py b/tests/test_compute.py index fedabd9..92a701b 100644 --- a/tests/test_compute.py +++ b/tests/test_compute.py @@ -5,6 +5,7 @@ from libcloud.compute.types import KeyPairDoesNotExistError, NodeState from libcloud_noderings.compute import NodeRingsNodeDriver +from tests.fakeapi import ACME_ID, ACME_OFFER, ACME_PLAN_ID, ACME_REGION_ID, PLAN_ID PUB = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExampleKey laptop" @@ -67,6 +68,53 @@ def test_unknown_offer_is_explained(compute): compute.create_node("web-1", "SC-GC-1C-1G-20", "ubuntu_24_04", location=nowhere, auth=NodeAuthPassword("x")) +@pytest.mark.parametrize("provider", [ACME_ID, "acme-hosting", "Acme Hosting", " acme HOSTING "]) +def test_create_node_from_the_named_provider(compute, fake, provider): + loc = compute.list_locations()[0] + compute.create_node("web-1", "SC-GC-1C-1G-20", "ubuntu_24_04", location=loc, auth=NodeAuthPassword("x"), ex_provider=provider) + body = fake.created_vm_bodies[-1] + assert body["planId"] == ACME_PLAN_ID and body["regionId"] == ACME_REGION_ID + + +def test_create_node_without_a_provider_takes_the_cheapest(compute, fake): + loc = compute.list_locations()[0] + compute.create_node("web-1", "SC-GC-1C-1G-20", "ubuntu_24_04", location=loc, auth=NodeAuthPassword("x")) + assert fake.created_vm_bodies[-1]["planId"] == PLAN_ID + + +def test_create_node_provider_id_wins_over_provider(compute, fake): + loc = compute.list_locations()[0] + compute.create_node( + "web-1", + "SC-GC-1C-1G-20", + "ubuntu_24_04", + location=loc, + auth=NodeAuthPassword("x"), + ex_provider_id=ACME_ID, + ex_provider="Nobody", + ) + assert fake.created_vm_bodies[-1]["planId"] == ACME_PLAN_ID + + +def test_create_node_fails_for_an_unknown_provider(compute, fake): + loc = compute.list_locations()[0] + with pytest.raises(LibcloudError, match="from provider Nobody Hosting"): + compute.create_node( + "web-1", "SC-GC-1C-1G-20", "ubuntu_24_04", location=loc, auth=NodeAuthPassword("x"), ex_provider="Nobody Hosting" + ) + assert not fake.created_vm_bodies + + +def test_create_node_refuses_a_provider_name_two_providers_share(compute, fake): + fake.extra_providers.append(dict(ACME_OFFER, organizationId="66666666-6666-6666-6666-666666666666")) + loc = compute.list_locations()[0] + with pytest.raises(LibcloudError, match="more than one provider is named acme hosting"): + compute.create_node( + "web-1", "SC-GC-1C-1G-20", "ubuntu_24_04", location=loc, auth=NodeAuthPassword("x"), ex_provider="acme hosting" + ) + assert not fake.created_vm_bodies + + def test_power_tags_and_destroy(compute, fake): loc = compute.list_locations()[0] node = compute.create_node("web-1", "SC-GC-1C-1G-20", "ubuntu_24_04", location=loc, auth=NodeAuthPassword("x")) @@ -103,3 +151,26 @@ def test_missing_token(monkeypatch): with pytest.raises(InvalidCredsError): NodeRingsNodeDriver() + + +class _Storefronts: + def __init__(self, error=None): + self.error = error + + def get_public_storefront(self, slug): + if self.error: + raise self.error + return {"slug": slug, "providerId": "prov-" + slug} + + +def test_resolve_provider(): + from libcloud_noderings._api.client import NodeRingsError + from libcloud_noderings._api.marketplace import resolve_provider + + assert resolve_provider(_Storefronts(), "") == (None, None) + assert resolve_provider(_Storefronts(), ACME_ID) == (ACME_ID, None) + assert resolve_provider(_Storefronts(), "acme") == ("prov-acme", None) + assert resolve_provider(_Storefronts(), " Acme Hosting ") == (None, "Acme Hosting") + assert resolve_provider(_Storefronts(NodeRingsError(404, 5, "not found")), "acme") == (None, "acme") + with pytest.raises(NodeRingsError): + resolve_provider(_Storefronts(NodeRingsError(503, 14, "unavailable")), "acme")