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
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ Orders a server, waits until it is provisioned and SSH answers, then runs
| `--city CITY` | City of the offer, such as `Ashburn`. See `knife noderings region list`. |
| `--billing-type TYPE` | `usage` (hourly, default), `subscription` or `free`. |
| `--sort ORDER` | `price` (cheapest, default) or `rating` (best rated). |
| `--provider-id ID` | Only consider offers from this provider. |
| `--hosting-provider PROVIDER` | Only consider offers from this provider: its ID, storefront slug (such as `acme-hosting`) or name (`"Acme Hosting"`, any case). |
| `--provider-id ID` | Only consider offers from the provider with this ID. Takes precedence over `--hosting-provider`. |
| `--plan-id ID`, `--region-id ID` | An exact plan and region, instead of plan, country and city. |
| `--distro DISTRO` | Operating system, `ubuntu_24_04` by default. See `knife noderings distro list`. |
| `--noderings-ssh-key NAME` | NodeRings SSH key to install. Repeat for more. Required. |
Expand All @@ -74,6 +75,10 @@ Orders a server, waits until it is provisioned and SSH answers, then runs
| `--noderings-tags a,b` | Tags on the server. |
| `--server-create-timeout SECONDS` | How long to wait for the server (default 900). |

Without `--hosting-provider` knife orders the cheapest matching offer (compute
price, then rating), so the provider can change between servers. A provider name
that more than one provider uses fails; give the ID or storefront slug then.

knife connects as `root` on port 22 and accepts the new server's host key on first
use; override with `--connection-user`, `--ssh-port` and `--ssh-verify-host-key`.
The node gets an Ohai hint file named `noderings` holding the server's ID and hostname, so recipes can check `hint?('noderings')`.
Expand Down
9 changes: 7 additions & 2 deletions lib/chef/knife/noderings_server_create.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,13 @@ class NoderingsServerCreate < Chef::Knife::Bootstrap
in: %w{usage subscription free},
default: "usage"

option :hosting_provider,
long: "--hosting-provider PROVIDER",
description: "Only consider offers from this provider, given by its ID, storefront slug or name (any case)."

option :provider_id,
long: "--provider-id ID",
description: "Only consider offers from this provider."
description: "Only consider offers from the provider with this ID. Takes precedence over --hosting-provider."

option :sort,
long: "--sort ORDER",
Expand Down Expand Up @@ -178,7 +182,8 @@ def select_offer(client)

plan_id, region_id, offer = noderings_call("finding an offer") do
compute.choose_offer(client, config[:plan], config[:country], config[:city],
billing_type: config[:billing_type], provider_id: config[:provider_id], sort: config[:sort])
billing_type: config[:billing_type], provider_id: config[:provider_id], sort: config[:sort],
provider: config[:hosting_provider])
end
[plan_id, region_id, "#{config[:plan]} from #{offer["provider_name"]} in #{config[:city]}, #{config[:country]}"]
end
Expand Down
4 changes: 4 additions & 0 deletions lib/knife-noderings/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,10 @@ def get_provider(provider_id)
get("/v1/marketplace/providers/#{KnifeNoderings.escape(provider_id)}")["provider"]
end

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

def list_distros
get("/v1/distros")["distros"] || []
end
Expand Down
59 changes: 51 additions & 8 deletions lib/knife-noderings/compute.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,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/

# 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 KnifeNoderings.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 @@ -67,9 +97,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/#{KnifeNoderings.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 @@ -80,6 +108,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 @@ -109,8 +145,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 > 0
Expand Down Expand Up @@ -208,14 +245,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
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/noderings_server_create_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,42 @@
expect(cmd).to have_received(:wait_for_sshd).with("192.0.2.50")
end

context "with --hosting-provider" do
def order_from(provider)
with = knife(described_class, args + ["--hosting-provider", provider])
allow(with).to receive(:wait_for_sshd)
with.plugin_validate_options!
with.plugin_create_instance!
with
end

[FakeNodeRings::ACME_ID, "acme-hosting", "Acme Hosting", " acme HOSTING "].each do |provider|
it "orders from the provider given as #{provider.inspect}" do
order_from(provider)
expect(@fake.created_vm_bodies.last).to include("planId" => FakeNodeRings::ACME_PLAN_ID, "regionId" => FakeNodeRings::ACME_REGION_ID)
end
end

it "orders the cheapest offer without one" do
cmd.plugin_validate_options!
cmd.plugin_create_instance!
expect(@fake.created_vm_bodies.last["planId"]).to eq FakeNodeRings::PLAN_ID
end

it "fails for an unknown provider" do
expect { order_from("Nobody Hosting") }.to raise_error(SystemExit)
expect(@stderr.string).to include("from provider Nobody Hosting")
expect(@fake.created_vm_bodies).to be_empty
end

it "refuses a provider name two providers share" do
@fake.extra_providers << FakeNodeRings::ACME_OFFER.merge("organizationId" => "66666666-6666-6666-6666-666666666666")
expect { order_from("acme hosting") }.to raise_error(SystemExit)
expect(@stderr.string).to include("more than one provider is named acme hosting")
expect(@fake.created_vm_bodies).to be_empty
end
end

it "sends the User-Agent and token" do
cmd.plugin_validate_options!
cmd.plugin_create_instance!
Expand Down