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
11 changes: 10 additions & 1 deletion documentation/noderings_vm.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ The [API properties](partial_api.md) also apply.
| `city` | String | | City of the offer, such as `Ashburn`. |
| `billing_type` | String | `usage` | `usage` (hourly), `subscription` (monthly) or `free`. |
| `sort` | String | `price` | Order the cheapest matching offer, or the best rated with `rating`. |
| `provider_id` | String | | Only consider offers from this provider. |
| `hosting_provider` | String | any provider | Only consider offers from this provider, given by its ID, storefront slug or name. See below. |
| `provider_id` | String | | Only consider offers from the provider with this ID. Takes precedence over `hosting_provider`. |
| `require_capabilities` | Array | `[]` | Only consider providers with these capabilities, such as `guest_firewall`. |
| `require_ipv6` | true, false | `false` | Only consider offers with IPv6. |
| `plan_id`, `region_id` | String | | An exact plan and region, instead of `plan`, `country` and `city`. |
Expand All @@ -50,6 +51,13 @@ offer that matches (or the best rated with `sort 'rating'`). Find what is sold i
the NodeRings console marketplace, or with
`knife noderings plan list` from [knife-noderings](https://github.com/noderings/knife-noderings).

Without `hosting_provider` the resource takes the cheapest offer (compute price,
then rating), so the provider can change between orders. Set `hosting_provider`
to keep it fixed. It takes 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 fails the run; give the ID or slug then. The property is not called
`provider` because Chef reserves that name on every resource.

The order carries an idempotency key, so a lost response is retried without
ordering twice.

Expand All @@ -68,6 +76,7 @@ noderings_vm 'web-1' do
plan 'SC-GC-1C-1G-20'
country 'United States'
city 'Ashburn'
hosting_provider 'acme-hosting'
distro 'debian_13'
ssh_keys ['deploy']
tags %w(web production)
Expand Down
4 changes: 4 additions & 0 deletions libraries/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,10 @@ def get_provider(provider_id)
get("/v1/marketplace/providers/#{NodeRingsCookbook.escape(provider_id)}")['provider']
end

def get_public_storefront(slug)
get("/v1/public/storefronts/#{NodeRingsCookbook.escape(slug)}")['storefront']
end

def list_distros
get('/v1/distros')['distros'] || []
end
Expand Down
59 changes: 51 additions & 8 deletions libraries/compute.rb
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,40 @@ def same_place?(region, country, city)
region['country'].to_s.casecmp?(country.to_s) && region['city'].to_s.casecmp?(city.to_s)
end

SLUG_RE = /\A[a-z0-9-]{1,80}\z/.freeze

# A provider ID, storefront slug or provider name -> [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.
def resolve_provider(client, provider)
value = provider.to_s.strip
return [nil, nil] if value.empty?
return [value, nil] if NodeRingsCookbook.uuid?(value)

provider_id = SLUG_RE.match?(value) ? storefront_provider_id(client, value) : ''
provider_id.empty? ? [nil, value] : [provider_id, nil]
end

# The provider ID of the public storefront with this slug, or '' if there is none.
def storefront_provider_id(client, slug)
(client.get_public_storefront(slug) || {})['providerId'].to_s
rescue APIError => e
raise unless e.not_found?

''
end

# Returns [offers, located]: offers sorted best first, and how many matched
# the location before the capability and IPv6 filters.
#
# provider is a provider ID, storefront slug or provider name (see
# resolve_provider); provider_id takes precedence over it.
def find_offers(client, plan_code, country, city, billing_type: 'usage', provider_id: nil,
require_capabilities: [], require_ipv6: false, sort: 'price')
require_capabilities: [], require_ipv6: false, sort: 'price', provider: nil)
provider_name = nil
provider_id, provider_name = resolve_provider(client, provider) if provider_id.to_s.empty? && !provider.to_s.strip.empty?
billing = BILLING_TYPES.fetch(billing_type.to_s, '')
found = []
if provider_id.to_s.empty?
Expand All @@ -65,9 +95,7 @@ def find_offers(client, plan_code, country, city, billing_type: 'usage', provide
p['ipv6AvailableInFilteredRegion'], p['planPrices'])
end
else
p = client.get(
"/v1/marketplace/providers/#{NodeRingsCookbook.escape(provider_id)}"
)
p = client.get_provider(provider_id) || {}
info = p['provider'] || {}
(p['availablePlans'] || []).each do |pl|
next if pl['planCode'] != plan_code || (!billing.empty? && pl['billingType'] != billing)
Expand All @@ -78,6 +106,14 @@ def find_offers(client, plan_code, country, city, billing_type: 'usage', provide
end
end
end
if provider_name
want = provider_name.downcase
found = found.select { |o| o['provider_name'].to_s.strip.downcase == want }
if found.map { |o| o['provider_id'] }.uniq.length > 1
raise UsageError, "more than one provider is named #{provider_name}; give its provider ID or " \
'storefront slug instead'
end
end
located = found.length
need = Array(require_capabilities)
out = found.select { |o| (need - o['capabilities']).empty? && (!require_ipv6 || o['ipv6']) }
Expand Down Expand Up @@ -107,8 +143,9 @@ def offer(info, plan_id, region_id, billing, ipv6, prices)
}
end

def no_offer_message(plan_code, country, city, billing_type, located)
def no_offer_message(plan_code, country, city, billing_type, located, provider = nil)
msg = "No offer for plan code #{plan_code} in #{city}, #{country}"
msg += " from provider #{provider}" unless provider.to_s.empty?
msg += " with billing type #{billing_type}" unless billing_type.to_s.empty?
msg += '.'
msg += " #{located} offer(s) matched the location but not the required capabilities or IPv6." if located.positive?
Expand Down Expand Up @@ -206,14 +243,20 @@ def translate_create_error(err)
end

# Returns [plan_id, region_id, offer] for the best matching offer.
#
# provider limits the offers to one provider, given by ID, storefront slug or name.
def choose_offer(client, plan_code, country, city, billing_type: 'usage', provider_id: nil,
require_capabilities: [], require_ipv6: false, sort: 'price')
require_capabilities: [], require_ipv6: false, sort: 'price', provider: nil)
offers, located = Marketplace.find_offers(
client, plan_code, country, city,
billing_type: billing_type, provider_id: provider_id,
require_capabilities: require_capabilities, require_ipv6: require_ipv6, sort: sort
require_capabilities: require_capabilities, require_ipv6: require_ipv6, sort: sort,
provider: provider
)
raise UsageError, Marketplace.no_offer_message(plan_code, country, city, billing_type, located) if offers.empty?
if offers.empty?
named = provider_id.to_s.empty? ? provider.to_s.strip : provider_id
raise UsageError, Marketplace.no_offer_message(plan_code, country, city, billing_type, located, named)
end

best = offers.first
[best['plan_id'], best['region_id'], best]
Expand Down
9 changes: 7 additions & 2 deletions resources/vm.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,12 @@
equal_to: %w(usage subscription free),
description: 'How the plan is billed'

property :hosting_provider, String,
description: 'Only consider offers from this provider, given by its ID, storefront slug or name (any case). ' \
'Left unset, the cheapest matching offer from any provider is ordered. (Chef reserves the name provider.)'

property :provider_id, String,
description: 'Only consider offers from this provider'
description: 'Only consider offers from the provider with this ID. Takes precedence over hosting_provider'

property :sort, String,
default: 'price',
Expand Down Expand Up @@ -143,7 +147,8 @@ def offer!
compute.choose_offer(noderings_client, new_resource.plan, new_resource.country, new_resource.city,
billing_type: new_resource.billing_type, provider_id: new_resource.provider_id,
require_capabilities: new_resource.require_capabilities,
require_ipv6: new_resource.require_ipv6, sort: new_resource.sort)
require_ipv6: new_resource.require_ipv6, sort: new_resource.sort,
provider: new_resource.hosting_provider)
end
[plan_id, region_id, "#{new_resource.plan} from #{offer['provider_name']} in #{new_resource.city}, #{new_resource.country}"]
end
Expand Down
36 changes: 35 additions & 1 deletion spec/support/fake_noderings.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,21 @@
class FakeNodeRings
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' => [], 'rating' => 3,
'planPrices' => [{ 'unitAmount' => '0.012', 'unitName' => 'per compute-hour' }]
}.freeze

attr_reader :calls, :ssh_keys, :zones, :records, :rulesets, :rules, :groups, :vms, :created_vm_bodies
# Status codes to return before handling the next matching request: { 'POST /v1/virtual-machines' => [502] }
attr_reader :failures
# More provider offers to list, such as a second provider with the same name.
attr_reader :extra_providers

def initialize
@calls = []
Expand All @@ -27,6 +38,7 @@ def initialize
@vms = {}
@created_vm_bodies = []
@failures = Hash.new { |h, k| h[k] = [] }
@extra_providers = []
@routes = [
['GET', %r{\A/v1/organization\z}, :get_org],
['GET', %r{\A/v1/ssh-keys\z}, :list_keys],
Expand All @@ -52,6 +64,8 @@ def initialize
['DELETE', %r{\A/v1/firewall/rules/([^/]+)\z}, :delete_rule],
['POST', %r{\A/v1/firewall/rules/([^/]+)/move\z}, :move_rule],
['GET', %r{\A/v1/marketplace/providers\z}, :list_providers],
['GET', %r{\A/v1/marketplace/providers/([^/]+)\z}, :get_provider],
['GET', %r{\A/v1/public/storefronts/([^/]+)\z}, :get_storefront],
['GET', %r{\A/v1/marketplace/plans/([^/]+)\z}, :get_plan],
['GET', %r{\A/v1/marketplace/plans\z}, :list_plans],
['GET', %r{\A/v1/marketplace/regions\z}, :list_regions],
Expand Down Expand Up @@ -137,7 +151,27 @@ def list_providers(q, _b)
'planPrices' => [{ 'unitAmount' => '0.007', 'unitName' => 'per compute-hour' },
{ 'unitAmount' => '0.0001', 'unitName' => 'per GB-hour storage' }]
},
] }]
ACME_OFFER,
] + @extra_providers }]
end

def get_provider(_q, _b, provider_id)
return err(404, 5, 'provider not found') unless provider_id == ACME_ID

[200, { 'provider' => {
'provider' => { 'organizationId' => ACME_ID, 'organizationName' => 'Acme Hosting', 'rating' => 3 },
'availablePlans' => [{
'planId' => ACME_PLAN_ID, 'planCode' => 'SC-GC-1C-1G-20', 'billingType' => 'BILLING_TYPE_USAGE',
'assetType' => 'ASSET_TYPE_VM', 'planPrices' => ACME_OFFER['planPrices'],
'regions' => [{ 'country' => 'United States', 'city' => 'Ashburn', 'regionId' => ACME_REGION_ID }]
}],
} }]
end

def get_storefront(_q, _b, slug)
return err(404, 5, 'storefront not found') unless slug == 'acme-hosting'

[200, { 'storefront' => { 'slug' => slug, 'providerId' => ACME_ID } }]
end

# -- SSH keys ----------------------------------------------------------------
Expand Down
36 changes: 36 additions & 0 deletions spec/unit/libraries/compute_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,42 @@
require_capabilities: ['guest_firewall'])[2]['provider_name']).to eq 'Cheap Host'
end

context 'with a provider' do
[FakeNodeRings::ACME_ID, 'acme-hosting', 'Acme Hosting', ' acme HOSTING '].each do |provider|
it "orders from the provider given as #{provider.inspect}" do
plan_id, region_id, offer = compute.choose_offer(client, 'SC-GC-1C-1G-20', 'United States', 'Ashburn',
provider: provider)
expect([plan_id, region_id, offer['provider_name']]).to eq [FakeNodeRings::ACME_PLAN_ID, FakeNodeRings::ACME_REGION_ID, 'Acme Hosting']
end
end

it 'takes the cheapest offer without one' do
expect(compute.choose_offer(client, 'SC-GC-1C-1G-20', 'United States', 'Ashburn', provider: '').first).to eq FakeNodeRings::PLAN_ID
end

it 'prefers provider_id when both are given' do
expect(compute.choose_offer(client, 'SC-GC-1C-1G-20', 'United States', 'Ashburn',
provider_id: FakeNodeRings::ACME_ID, provider: 'Cheap Host').first).to eq FakeNodeRings::ACME_PLAN_ID
end

it 'fails for an unknown provider' do
expect { compute.choose_offer(client, 'SC-GC-1C-1G-20', 'United States', 'Ashburn', provider: 'Nobody Hosting') }
.to raise_error(NodeRingsCookbook::UsageError, /in Ashburn, United States from provider Nobody Hosting/)
end

it 'refuses a provider name two providers share' do
fake.extra_providers << FakeNodeRings::ACME_OFFER.merge('organizationId' => '66666666-6666-6666-6666-666666666666')
expect { compute.choose_offer(client, 'SC-GC-1C-1G-20', 'United States', 'Ashburn', provider: 'acme hosting') }
.to raise_error(NodeRingsCookbook::UsageError, /more than one provider is named acme hosting; give its provider ID or storefront slug/)
end

it 'passes on storefront errors other than not found' do
fake.failures['GET /v1/public/storefronts/acme-hosting'] = [403]
expect { compute.choose_offer(client, 'SC-GC-1C-1G-20', 'United States', 'Ashburn', provider: 'acme-hosting') }
.to raise_error(NodeRingsCookbook::APIError)
end
end

it 'explains a missing offer' do
expect { compute.choose_offer(client, 'P', 'United States', 'Nowhere') }
.to raise_error(NodeRingsCookbook::UsageError, /No offer for plan code P in Nowhere/)
Expand Down
17 changes: 17 additions & 0 deletions spec/unit/resources/vm_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,23 @@ def order_existing(distro = 'DISTRO_UBUNTU_24_04')
end
end

context 'ordering from a named provider' do
recipe do
noderings_vm 'web-1' do
plan 'SC-GC-1C-1G-20'
country 'United States'
city 'Ashburn'
hosting_provider 'acme-hosting'
ssh_keys ['laptop']
end
end

it 'orders the offer of that provider' do
chef_run
expect(@fake.created_vm_bodies.last).to include('planId' => FakeNodeRings::ACME_PLAN_ID, 'regionId' => FakeNodeRings::ACME_REGION_ID)
end
end

context 'an existing VM' do
before { order_existing }

Expand Down