Skip to content
Merged
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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
Expand All @@ -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
Expand Down
9 changes: 8 additions & 1 deletion docs/topics/cloud.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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. |
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion docs/topics/states.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions src/saltext/noderings/clouds/noderings_mod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 [])
Expand Down
8 changes: 8 additions & 0 deletions src/saltext/noderings/modules/noderings_mod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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):
Expand All @@ -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")
Expand Down
12 changes: 12 additions & 0 deletions src/saltext/noderings/states/noderings_mod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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"):
Expand Down Expand Up @@ -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,
)
Expand Down
3 changes: 3 additions & 0 deletions src/saltext/noderings/utils/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
38 changes: 25 additions & 13 deletions src/saltext/noderings/utils/compute.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down
53 changes: 51 additions & 2 deletions src/saltext/noderings/utils/marketplace.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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"))
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 = [
Expand Down Expand Up @@ -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 += "."
Expand Down
28 changes: 28 additions & 0 deletions tests/unit/clouds/test_noderings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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")
Expand Down
Loading
Loading