diff --git a/README.md b/README.md index 377bfac..1c94284 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,7 @@ noderings-ashburn-small: location: United States/Ashburn image: ubuntu_24_04 billing_type: usage # hourly, from prepaid credit + hosting_provider: acme-hosting # optional; the cheapest provider otherwise ssh_keys: [laptop] # stored in NodeRings private_key: /root/.ssh/id_ed25519 ``` @@ -69,6 +70,8 @@ salt-cloud -d web-1 `salt-cloud --list-sizes|--list-locations|--list-images my-noderings` list what you can order. +Without `hosting_provider` the cheapest matching offer is ordered, so the provider can change between servers. `hosting_provider` keeps it fixed: give the provider's ID, its storefront slug (such as `acme-hosting`) or its name (`Acme Hosting`, any case). A name that more than one provider uses is an error; give the ID or slug then. The key is not called `provider` because that names the Salt Cloud provider block in a profile. `noderings.create_vm` and `noderings.vm_present` take the same `hosting_provider` argument. + ## Manage resources with the execution module ```bash diff --git a/docs/topics/cloud.md b/docs/topics/cloud.md index 7f0a0e1..589b5b5 100644 --- a/docs/topics/cloud.md +++ b/docs/topics/cloud.md @@ -26,6 +26,7 @@ noderings-ashburn-small: location: United States/Ashburn # Country/City image: ubuntu_24_04 # distro billing_type: usage # hourly, from prepaid credit + hosting_provider: acme-hosting # optional: ID, storefront slug or name ssh_keys: [laptop] # SSH keys stored in NodeRings (a key or a password is required) private_key: /root/.ssh/id_ed25519 firewall_ruleset: web # optional @@ -39,7 +40,8 @@ noderings-ashburn-small: | `image` | Distro. `salt-cloud --list-images my-noderings` lists them. | | `billing_type` | `usage` (hourly, default), `subscription` or `free`. | | `plan_id`, `region_id` | Order one exact offer instead of the cheapest for `size` and `location`. | -| `provider_id` | Only consider offers from this hosting provider. | +| `hosting_provider` | Only order from this hosting provider: its provider ID, its storefront slug (such as `acme-hosting`) or its name (`Acme Hosting`, any case). A name that more than one provider uses fails the order; give the ID or slug then. Without it the cheapest offer wins, so the provider can change between servers. | +| `provider_id` | Only consider offers from this hosting provider ID. Takes precedence over `hosting_provider`. | | `sort` | `price` (default) or `rating`. | | `ssh_keys` | Names of SSH keys stored in NodeRings. The API needs a key or a `password`. | | `private_key` | Private key matching one of `ssh_keys`, used for the bootstrap. | @@ -48,6 +50,11 @@ noderings-ashburn-small: | `deploy` | `False` to skip the minion bootstrap. | | `wait_timeout` | Seconds to wait for the server to be running (default 900). | +The hosting provider key is `hosting_provider`, not `provider`: in a Salt Cloud +profile `provider` names the provider block (`my-noderings` above). The execution +module and the `vm_present` state use the same name, also because Salt reserves +`provider` as a state argument. + ## Use ```bash diff --git a/docs/topics/states.md b/docs/topics/states.md index 7066a73..d18ae27 100644 --- a/docs/topics/states.md +++ b/docs/topics/states.md @@ -54,7 +54,7 @@ www: |---|---| | `tags`, `firewall_ruleset`, `power_state` | Updated in place | | `distro` | Reinstalls the server only with `allow_reinstall: True`, because it erases the disk; otherwise the state fails and says so | -| `plan_code`, `plan_id`, `region_id` | Only used to order; an existing server is never moved | +| `plan_code`, `plan_id`, `region_id`, `hosting_provider` | Only used to order; an existing server is never moved | Firewall rules run top to bottom, and traffic that matches no rule is accepted, so end a ruleset with a drop rule. Each rule takes one port or one range such diff --git a/src/saltext/noderings/clouds/noderings_mod.py b/src/saltext/noderings/clouds/noderings_mod.py index cc9c80e..686768b 100644 --- a/src/saltext/noderings/clouds/noderings_mod.py +++ b/src/saltext/noderings/clouds/noderings_mod.py @@ -315,6 +315,9 @@ def create(vm_): provider_id=_profile_value(vm_, "provider_id"), require_capabilities=["guest_firewall"] if ruleset_id else [], sort=_profile_value(vm_, "sort", "price"), + # ``provider`` names the Salt Cloud provider block, so the hosting + # provider has its own key. + provider=_profile_value(vm_, "hosting_provider"), ) log.info("Ordering %s from %s", name, offer.get("provider_name")) key_ids = compute.resolve_ssh_keys(client, _profile_value(vm_, "ssh_keys") or []) diff --git a/src/saltext/noderings/modules/noderings_mod.py b/src/saltext/noderings/modules/noderings_mod.py index 7c5eef0..7ccd10a 100644 --- a/src/saltext/noderings/modules/noderings_mod.py +++ b/src/saltext/noderings/modules/noderings_mod.py @@ -737,6 +737,7 @@ def create_vm( plan_id=None, region_id=None, provider_id=None, + hosting_provider=None, sort="price", wait=True, wait_timeout=900, @@ -750,11 +751,17 @@ def create_vm( and ``region_id`` from ``noderings.list_offers``. ``billing_type=usage`` bills by the hour from prepaid credit and stops when the VM is deleted. + ``hosting_provider`` orders only from one hosting provider: its provider ID, + its storefront slug (such as ``acme-hosting``) or its name (``Acme Hosting``, + any case). A name that more than one provider uses is an error; give the ID + or slug then. ``provider_id`` takes precedence. + CLI Example: .. code-block:: bash salt '*' noderings.create_vm web-1 plan_code=SC-GC-1C-1G-20 country="United States" city=Ashburn ssh_keys='["laptop"]' + salt '*' noderings.create_vm web-1 plan_code=SC-GC-1C-1G-20 country="United States" city=Ashburn hosting_provider=acme-hosting ssh_keys='["laptop"]' """ client = _client(profile) if _vm(client, name): @@ -777,6 +784,7 @@ def create_vm( provider_id=provider_id, require_capabilities=caps, sort=sort, + provider=hosting_provider, ) elif not region_id: raise SaltInvocationError("plan_id needs region_id") diff --git a/src/saltext/noderings/states/noderings_mod.py b/src/saltext/noderings/states/noderings_mod.py index 0bddf8b..fe511fd 100644 --- a/src/saltext/noderings/states/noderings_mod.py +++ b/src/saltext/noderings/states/noderings_mod.py @@ -399,6 +399,7 @@ def vm_present( plan_id=None, region_id=None, provider_id=None, + hosting_provider=None, password=None, wait_timeout=900, profile="noderings", @@ -424,6 +425,16 @@ def vm_present( firewall_ruleset Name or ID of a ruleset to attach. ``""`` detaches the current one; ``None`` (the default) leaves it alone. + + hosting_provider + Order only from this hosting provider: its provider ID, its storefront + slug (such as ``acme-hosting``) or its name (``Acme Hosting``, any + case). A name that more than one provider uses fails the state; give + the ID or slug then. Without it the cheapest offer from any provider is + ordered, so the provider can change between servers. ``provider_id`` + takes precedence. Only used to order; an existing server is never + moved. (It is not called ``provider`` because Salt reserves that state + argument.) """ ret = _ret(name) if power_state not in ("running", "stopped"): @@ -458,6 +469,7 @@ def vm_present( plan_id=plan_id, region_id=region_id, provider_id=provider_id, + hosting_provider=hosting_provider, wait_timeout=wait_timeout, profile=profile, ) diff --git a/src/saltext/noderings/utils/client.py b/src/saltext/noderings/utils/client.py index 5f4e0f3..0f51e4c 100644 --- a/src/saltext/noderings/utils/client.py +++ b/src/saltext/noderings/utils/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/saltext/noderings/utils/compute.py b/src/saltext/noderings/utils/compute.py index 2b881a7..caaede2 100644 --- a/src/saltext/noderings/utils/compute.py +++ b/src/saltext/noderings/utils/compute.py @@ -14,6 +14,7 @@ from saltext.noderings.utils.client import new_uuid from saltext.noderings.utils.client import snake from saltext.noderings.utils.client import trim_enum +from saltext.noderings.utils.marketplace import NoOfferError from saltext.noderings.utils.marketplace import find_offers from saltext.noderings.utils.marketplace import no_offer_message from saltext.noderings.utils.marketplace import offer_view @@ -104,21 +105,32 @@ 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/saltext/noderings/utils/marketplace.py b/src/saltext/noderings/utils/marketplace.py index 92964cb..0fb51af 100644 --- a/src/saltext/noderings/utils/marketplace.py +++ b/src/saltext/noderings/utils/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 saltext.noderings.utils.client import NodeRingsError +from saltext.noderings.utils.client import is_not_found +from saltext.noderings.utils.client import is_uuid from saltext.noderings.utils.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/tests/unit/clouds/test_noderings.py b/tests/unit/clouds/test_noderings.py index 3b7ebbd..b93b203 100644 --- a/tests/unit/clouds/test_noderings.py +++ b/tests/unit/clouds/test_noderings.py @@ -5,6 +5,11 @@ from salt.exceptions import SaltCloudSystemExit import saltext.noderings.clouds.noderings_mod as noderings_cloud +from tests.unit.fakeapi import ACME_ID +from tests.unit.fakeapi import ACME_OFFER +from tests.unit.fakeapi import ACME_PLAN_ID +from tests.unit.fakeapi import ACME_REGION_ID +from tests.unit.fakeapi import PLAN_ID PROVIDER = "my-noderings" @@ -99,6 +104,29 @@ def test_create_rejects_duplicates_and_bad_profiles(api): # pylint: disable=unu noderings_cloud.create(_vm_(name="web-3", location="United States/Nowhere")) +@pytest.mark.parametrize("provider", [ACME_ID, "acme-hosting", "Acme Hosting", " acme HOSTING "]) +def test_create_orders_from_the_hosting_provider(api, provider): + noderings_cloud.create(_vm_(hosting_provider=provider)) + body = api.created_vm_bodies[-1] + assert body["planId"] == ACME_PLAN_ID and body["regionId"] == ACME_REGION_ID + + +def test_create_without_a_hosting_provider_takes_the_cheapest(api): + noderings_cloud.create(_vm_()) + assert api.created_vm_bodies[-1]["planId"] == PLAN_ID + + +def test_create_fails_for_an_unknown_or_shared_provider_name(api): + with pytest.raises(SaltCloudSystemExit, match="from provider Nobody Hosting"): + noderings_cloud.create(_vm_(hosting_provider="Nobody Hosting")) + api.extra_providers.append( + dict(ACME_OFFER, organizationId="66666666-6666-6666-6666-666666666666") + ) + with pytest.raises(SaltCloudSystemExit, match="more than one provider is named acme hosting"): + noderings_cloud.create(_vm_(hosting_provider="acme hosting")) + assert not api.created_vm_bodies + + def test_call_guards(api): # pylint: disable=unused-argument with pytest.raises(SaltCloudSystemExit): noderings_cloud.list_nodes(call="action") diff --git a/tests/unit/fakeapi.py b/tests/unit/fakeapi.py index 854b59e..d233bc2 100644 --- a/tests/unit/fakeapi.py +++ b/tests/unit/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/unit/modules/test_noderings.py b/tests/unit/modules/test_noderings.py index 7997aa1..bf26fe9 100644 --- a/tests/unit/modules/test_noderings.py +++ b/tests/unit/modules/test_noderings.py @@ -2,6 +2,10 @@ from salt.exceptions import SaltInvocationError import saltext.noderings.modules.noderings_mod as noderings_module +from tests.unit.fakeapi import ACME_ID +from tests.unit.fakeapi import ACME_OFFER +from tests.unit.fakeapi import ACME_PLAN_ID +from tests.unit.fakeapi import ACME_REGION_ID from tests.unit.fakeapi import PLAN_ID from tests.unit.fakeapi import REGION_ID @@ -128,6 +132,41 @@ def test_create_vm_picks_offer_and_keys(api): assert len(body["sshKeyIds"]) == 1 and body["idempotencyKey"] +OFFER = {"plan_code": "SC-GC-1C-1G-20", "country": "United States", "city": "Ashburn"} + + +@pytest.mark.parametrize("provider", [ACME_ID, "acme-hosting", "Acme Hosting", " acme HOSTING "]) +def test_create_vm_from_the_named_provider(api, provider): + noderings_module.create_vm("web-1", hosting_provider=provider, **OFFER) + body = api.created_vm_bodies[-1] + assert body["planId"] == ACME_PLAN_ID and body["regionId"] == ACME_REGION_ID + + +def test_create_vm_without_a_provider_takes_the_cheapest(api): + noderings_module.create_vm("web-1", **OFFER) + assert api.created_vm_bodies[-1]["planId"] == PLAN_ID + + +def test_create_vm_provider_id_wins_over_hosting_provider(api): + noderings_module.create_vm("web-1", provider_id=ACME_ID, hosting_provider="Nobody", **OFFER) + assert api.created_vm_bodies[-1]["planId"] == ACME_PLAN_ID + + +def test_create_vm_fails_for_an_unknown_provider(api): + with pytest.raises(SaltInvocationError, match="from provider Nobody Hosting"): + noderings_module.create_vm("web-1", hosting_provider="Nobody Hosting", **OFFER) + assert not api.created_vm_bodies + + +def test_create_vm_refuses_a_provider_name_two_providers_share(api): + api.extra_providers.append( + dict(ACME_OFFER, organizationId="66666666-6666-6666-6666-666666666666") + ) + with pytest.raises(SaltInvocationError, match="more than one provider is named acme hosting"): + noderings_module.create_vm("web-1", hosting_provider="acme hosting", **OFFER) + assert not api.created_vm_bodies + + def test_create_vm_errors(api): # pylint: disable=unused-argument with pytest.raises(SaltInvocationError, match="No offer"): noderings_module.create_vm( diff --git a/tests/unit/states/test_noderings.py b/tests/unit/states/test_noderings.py index 5912b3c..e86cdd7 100644 --- a/tests/unit/states/test_noderings.py +++ b/tests/unit/states/test_noderings.py @@ -2,6 +2,7 @@ import saltext.noderings.modules.noderings_mod as noderings_module import saltext.noderings.states.noderings_mod as noderings_state +from tests.unit.fakeapi import ACME_PLAN_ID from tests.unit.fakeapi import PLAN_ID from tests.unit.fakeapi import REGION_ID @@ -48,6 +49,31 @@ def test_test_mode_changes_nothing(api, test_mode): # pylint: disable=unused-ar assert api.writes() == [] +@pytest.mark.parametrize("provider", [None, "acme-hosting", "Acme Hosting"]) +def test_vm_present_orders_from_the_hosting_provider(api, provider): + ret = noderings_state.vm_present( + "web-1", + plan_code="SC-GC-1C-1G-20", + country="United States", + city="Ashburn", + hosting_provider=provider, + ) + assert ret["result"] is True and ret["changes"]["old"] is None + assert api.created_vm_bodies[-1]["planId"] == (ACME_PLAN_ID if provider else PLAN_ID) + + +def test_vm_present_fails_for_an_unknown_provider(api): + ret = noderings_state.vm_present( + "web-1", + plan_code="SC-GC-1C-1G-20", + country="United States", + city="Ashburn", + hosting_provider="Nobody Hosting", + ) + assert ret["result"] is False and "from provider Nobody Hosting" in ret["comment"] + assert not api.created_vm_bodies + + def test_dns_zone_and_records(api): # pylint: disable=unused-argument assert noderings_state.dns_zone_present("example.com", dnssec=True)["changes"]["dnssec"] assert not noderings_state.dns_zone_present("example.com", dnssec=True)["changes"] diff --git a/tests/unit/utils/test_marketplace.py b/tests/unit/utils/test_marketplace.py index 4218a9a..5fe24b7 100644 --- a/tests/unit/utils/test_marketplace.py +++ b/tests/unit/utils/test_marketplace.py @@ -1,4 +1,7 @@ +import pytest + from saltext.noderings.utils import marketplace +from saltext.noderings.utils.client import NodeRingsError def test_main_price_prefers_compute_meter(): @@ -59,3 +62,25 @@ def test_find_offers_filters_and_sorts(): offers, located = marketplace.find_offers(m, "X", "Germany", "Frankfurt", sort="rating") assert [o["provider_name"] for o in offers] == ["c", "a", "b"] assert offers[0]["region_id"] == "region-c" + + +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(): + uuid = "33333333-3333-3333-3333-333333333333" + assert marketplace.resolve_provider(Storefronts(), "") == (None, None) + assert marketplace.resolve_provider(Storefronts(), uuid) == (uuid, None) + assert marketplace.resolve_provider(Storefronts(), "acme") == ("prov-acme", None) + assert marketplace.resolve_provider(Storefronts(), " Acme Hosting ") == (None, "Acme Hosting") + not_found = NodeRingsError(404, 5, "storefront not found") + assert marketplace.resolve_provider(Storefronts(not_found), "acme") == (None, "acme") + with pytest.raises(NodeRingsError): + marketplace.resolve_provider(Storefronts(NodeRingsError(503, 14, "unavailable")), "acme")