vagrant-noderings 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,412 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright:: NodeRings
5
+ # License:: Apache-2.0
6
+ #
7
+ # Marketplace offer lookup and virtual machine lifecycle helpers.
8
+
9
+ require_relative "client"
10
+
11
+ module NoderingsVagrant
12
+ BILLING_TYPES = {
13
+ "usage" => "BILLING_TYPE_USAGE",
14
+ "subscription" => "BILLING_TYPE_SUBSCRIPTION",
15
+ "free" => "BILLING_TYPE_FREE",
16
+ }.freeze
17
+ NONCE_TAG_PREFIX = "vagrant-create-"
18
+ DEFAULT_WAIT_TIMEOUT = 900
19
+
20
+ # Marketplace offers: turn a plan code and a city into a plan and region ID.
21
+ module Marketplace
22
+ module_function
23
+
24
+ def amount(price)
25
+ Float(price["unitAmount"])
26
+ rescue ArgumentError, TypeError
27
+ nil
28
+ end
29
+
30
+ # The price that best represents what the plan costs, for sorting.
31
+ #
32
+ # Usage plans carry several meters (compute-hours, storage, traffic, IPs);
33
+ # comparing the smallest of them would rank by the cheapest meter, not the
34
+ # cheapest server. Prefer the compute meter, then a flat price.
35
+ def main_price(prices)
36
+ prices = Array(prices).reject { |p| amount(p).nil? }
37
+ return Float::INFINITY if prices.empty?
38
+
39
+ compute = prices.select { |p| p["unitName"].to_s.downcase.include?("compute") }
40
+ return compute.map { |p| amount(p) }.min unless compute.empty?
41
+
42
+ flat = prices.select do |p|
43
+ p["pricingModel"].to_s.end_with?("FLAT", "FLAT_RATE", "FIXED", "PER_UNIT") ||
44
+ p["chargeTiming"].to_s.end_with?("IN_ADVANCE")
45
+ end
46
+ return flat.map { |p| amount(p) }.min unless flat.empty?
47
+
48
+ prices.map { |p| amount(p) }.min
49
+ end
50
+
51
+ def same_place?(region, country, city)
52
+ region["country"].to_s.casecmp?(country.to_s) && region["city"].to_s.casecmp?(city.to_s)
53
+ end
54
+
55
+ # Returns [offers, located]: offers sorted best first, and how many matched
56
+ # the location before the capability and IPv6 filters.
57
+ def find_offers(client, plan_code, country, city, billing_type: "usage", provider_id: nil,
58
+ require_capabilities: [], require_ipv6: false, sort: "price")
59
+ billing = BILLING_TYPES.fetch(billing_type.to_s, "")
60
+ found = []
61
+ if provider_id.to_s.empty?
62
+ client.list_providers(plan_code, country, city, billing_type: billing.empty? ? nil : billing,
63
+ ipv6_only: require_ipv6).each do |p|
64
+ regions = p["planRegions"] || []
65
+ region = regions.find { |r| same_place?(r, country, city) } || regions.first || {}
66
+ found << offer(p, p["planId"], region["regionId"], billing,
67
+ p["ipv6AvailableInFilteredRegion"], p["planPrices"])
68
+ end
69
+ else
70
+ p = client.get(
71
+ "/v1/marketplace/providers/#{NoderingsVagrant.escape(provider_id)}"
72
+ )
73
+ info = p["provider"] || {}
74
+ (p["availablePlans"] || []).each do |pl|
75
+ next if pl["planCode"] != plan_code || (!billing.empty? && pl["billingType"] != billing)
76
+ next if pl["assetType"] && pl["assetType"] != "ASSET_TYPE_VM"
77
+
78
+ (pl["regions"] || []).select { |r| same_place?(r, country, city) }.each do |r|
79
+ found << offer(info, pl["planId"], r["regionId"], pl["billingType"], p["hasIpv6"], pl["planPrices"])
80
+ end
81
+ end
82
+ end
83
+ located = found.length
84
+ need = Array(require_capabilities)
85
+ out = found.select { |o| (need - o["capabilities"]).empty? && (!require_ipv6 || o["ipv6"]) }
86
+ out = out.sort_by do |o|
87
+ price = main_price(o["prices"])
88
+ if sort.to_s == "rating"
89
+ [-o["rating"], price, o["provider_name"].to_s, o["plan_id"].to_s]
90
+ else
91
+ [price, -o["rating"], o["provider_name"].to_s, o["plan_id"].to_s]
92
+ end
93
+ end
94
+ [out, located]
95
+ end
96
+
97
+ def offer(info, plan_id, region_id, billing, ipv6, prices)
98
+ {
99
+ "provider_id" => info["organizationId"],
100
+ "provider_name" => info["organizationName"],
101
+ "plan_id" => plan_id,
102
+ "region_id" => region_id,
103
+ "billing_type" => NoderingsVagrant.trim_enum(billing, "BILLING_TYPE_"),
104
+ "capabilities" => info["capabilities"] || [],
105
+ "ipv6" => ipv6 ? true : false,
106
+ "rating" => info["rating"].to_f,
107
+ "total_reviews" => info["totalReviews"].to_i,
108
+ "prices" => prices || [],
109
+ }
110
+ end
111
+
112
+ def no_offer_message(plan_code, country, city, billing_type, located)
113
+ msg = "No offer for plan code #{plan_code} in #{city}, #{country}"
114
+ msg += " with billing type #{billing_type}" unless billing_type.to_s.empty?
115
+ msg += "."
116
+ msg += " #{located} offer(s) matched the location but not the required capabilities or IPv6." if located > 0
117
+ "#{msg} List what is sold in the NodeRings console marketplace, or with the API at /v1/marketplace/plans."
118
+ end
119
+ end
120
+
121
+ # Virtual machine helpers.
122
+ module Compute
123
+ module_function
124
+
125
+ def power_state(machine)
126
+ op = (machine || {})["operationStatus"].to_s
127
+ return "running" if %w{OPERATION_STATUS_STARTED OPERATION_STATUS_RESTARTED}.include?(op)
128
+ return "stopped" if op == "OPERATION_STATUS_STOPPED"
129
+
130
+ t = NoderingsVagrant.trim_enum(op, "OPERATION_STATUS_")
131
+ t.empty? ? "unknown" : t
132
+ end
133
+
134
+ # ubuntu-24.04, Ubuntu_24_04 and DISTRO_UBUNTU_24_04 -> ubuntu_24_04
135
+ def normalize_distro(distro)
136
+ distro.to_s.strip.downcase.delete_prefix("distro_").tr(".-", "__")
137
+ end
138
+
139
+ def distro_enum(distro)
140
+ "DISTRO_#{normalize_distro(distro).upcase}"
141
+ end
142
+
143
+ def user_tags(machine)
144
+ Array((machine || {})["tags"]).reject { |t| t.start_with?(NONCE_TAG_PREFIX) }.sort
145
+ end
146
+
147
+ # The VM as a plain hash with friendly fields.
148
+ def view(machine)
149
+ return {} if machine.nil?
150
+
151
+ {
152
+ "id" => machine["id"],
153
+ "hostname" => machine["hostname"],
154
+ "ipv4" => machine["ipv4"],
155
+ "ipv6" => machine["ipv6"],
156
+ "power_state" => power_state(machine),
157
+ "distro" => NoderingsVagrant.trim_enum(machine["distro"], "DISTRO_"),
158
+ "plan_code" => machine["planCode"],
159
+ "plan_id" => machine["planId"],
160
+ "region_id" => machine["regionId"],
161
+ "billing_type" => NoderingsVagrant.trim_enum(machine["planBillingType"], "BILLING_TYPE_"),
162
+ "provisioning_status" => NoderingsVagrant.trim_enum(machine["crStatus"], "CR_STATUS_"),
163
+ "firewall_ruleset_id" => machine["firewallRulesetId"],
164
+ "tags" => user_tags(machine),
165
+ }
166
+ end
167
+
168
+ # The VM with this ID or unique hostname, or nil.
169
+ def find_vm(client, name_or_id)
170
+ if NoderingsVagrant.uuid?(name_or_id)
171
+ begin
172
+ return client.get_virtual_machine(name_or_id)
173
+ rescue APIError => e
174
+ return if e.not_found?
175
+
176
+ raise
177
+ end
178
+ end
179
+ matches = client.list_virtual_machines.select { |v| v["hostname"] == name_or_id }
180
+ if matches.length > 1
181
+ raise UsageError, "#{matches.length} virtual machines are named #{name_or_id}; use the ID of " \
182
+ "the one you mean: #{matches.map { |v| v["id"] }.join(", ")}"
183
+ end
184
+ return if matches.empty?
185
+
186
+ # List entries omit some details; read the full VM.
187
+ client.get_virtual_machine(matches.first["id"])
188
+ end
189
+
190
+ def translate_create_error(err)
191
+ msg = err.message
192
+ low = msg.downcase
193
+ if low.include?("payment method")
194
+ msg += ". Add a payment method to the organization in the NodeRings console. Paid plans, " \
195
+ "including usage-billed ones, need one."
196
+ elsif low.include?("runway") || low.include?("insufficient")
197
+ msg += ". Top up the organization's credit balance, or choose a cheaper plan."
198
+ elsif low.include?("no vm template")
199
+ msg += ". This provider has no image for the chosen distro in this region. Pick another distro, or another offer."
200
+ elsif low.include?("capacity") || low.include?("marketplace-ready node")
201
+ msg += ". The region is out of capacity for this plan. Try another provider or city."
202
+ end
203
+ if err.is_a?(APIError) && err.quota?
204
+ msg += ". The organization has reached its virtual machine quota. Delete unused VMs or ask " \
205
+ "NodeRings support to raise the limit."
206
+ end
207
+ msg
208
+ end
209
+
210
+ # Returns [plan_id, region_id, offer] for the best matching offer.
211
+ def choose_offer(client, plan_code, country, city, billing_type: "usage", provider_id: nil,
212
+ require_capabilities: [], require_ipv6: false, sort: "price")
213
+ offers, located = Marketplace.find_offers(
214
+ client, plan_code, country, city,
215
+ billing_type: billing_type, provider_id: provider_id,
216
+ require_capabilities: require_capabilities, require_ipv6: require_ipv6, sort: sort
217
+ )
218
+ raise UsageError, Marketplace.no_offer_message(plan_code, country, city, billing_type, located) if offers.empty?
219
+
220
+ best = offers.first
221
+ [best["plan_id"], best["region_id"], best]
222
+ end
223
+
224
+ # SSH key names or IDs -> IDs.
225
+ def resolve_ssh_keys(client, keys)
226
+ keys = Array(keys)
227
+ return [] if keys.empty?
228
+
229
+ existing = client.list_ssh_keys
230
+ keys.map do |key|
231
+ match = existing.find { |k| k["id"] == key || k["name"] == key }
232
+ raise UsageError, "no NodeRings SSH key is named #{key}; add it in the NodeRings console, or leave ssh_keys unset to use a key Vagrant generates" unless match
233
+
234
+ match["id"]
235
+ end
236
+ end
237
+
238
+ # A firewall ruleset name or ID -> ID.
239
+ def resolve_ruleset(client, ruleset)
240
+ return "" if ruleset.to_s.empty?
241
+
242
+ rs = client.list_firewall_rulesets.find { |r| [r["id"], r["name"]].include?(ruleset) }
243
+ raise UsageError, "no NodeRings firewall ruleset is named #{ruleset}" unless rs
244
+
245
+ rs["id"]
246
+ end
247
+
248
+ def waiter(client, timeout)
249
+ Waiter.new(timeout, sleeper: ->(s) { client.sleep_for(s) })
250
+ end
251
+
252
+ def wait_provisioned(client, vm_id, timeout = DEFAULT_WAIT_TIMEOUT)
253
+ waiter(client, timeout).wait("virtual machine #{vm_id} to be provisioned") do
254
+ vm = client.get_virtual_machine(vm_id)
255
+ case vm["crStatus"]
256
+ when "CR_STATUS_APPLIED" then [true, vm]
257
+ when "CR_STATUS_FAILED"
258
+ raise UsageError, "provisioning of virtual machine #{vm_id} failed. The API does not report " \
259
+ "why; delete it and try another offer, or contact the provider"
260
+ else [false, nil]
261
+ end
262
+ end
263
+ end
264
+
265
+ # Waits until the VM is provisioned and has an IP address, without waiting
266
+ # for the power state; tools that go on to log in check SSH themselves.
267
+ def wait_address(client, vm_id, timeout = DEFAULT_WAIT_TIMEOUT)
268
+ vm = wait_provisioned(client, vm_id, timeout)
269
+ return vm unless vm["ipv4"].to_s.empty? && vm["ipv6"].to_s.empty?
270
+
271
+ waiter(client, timeout).wait("virtual machine #{vm_id} to get an IP address") do
272
+ vm = client.get_virtual_machine(vm_id)
273
+ [!(vm["ipv4"].to_s.empty? && vm["ipv6"].to_s.empty?), vm]
274
+ end
275
+ end
276
+
277
+ def wait_idle(client, vm_id, what, timeout = DEFAULT_WAIT_TIMEOUT)
278
+ waiter(client, timeout).wait(what) do
279
+ vm = client.get_virtual_machine(vm_id)
280
+ [yield(vm) && vm["crStatus"] != "CR_STATUS_PROCESSING", vm]
281
+ end
282
+ end
283
+
284
+ # Waits while the VM is in a transitional power state (created, reinstalling).
285
+ def wait_settled(client, vm_id, timeout = DEFAULT_WAIT_TIMEOUT)
286
+ wait_idle(client, vm_id, "the virtual machine to finish booting", timeout) do |vm|
287
+ %w{running stopped}.include?(power_state(vm))
288
+ end
289
+ end
290
+
291
+ # want: 'running', 'stopped' or 'restarted'
292
+ def set_power(client, vm_id, want, wait: true, timeout: DEFAULT_WAIT_TIMEOUT)
293
+ action = { "running" => "start", "stopped" => "stop", "restarted" => "restart" }.fetch(want)
294
+ waiter(client, timeout).retry_busy { client.vm_action(vm_id, action) }
295
+ return client.get_virtual_machine(vm_id) unless wait
296
+
297
+ target = want == "restarted" ? "running" : want
298
+ wait_idle(client, vm_id, "the virtual machine to be #{target}", timeout) { |vm| power_state(vm) == target }
299
+ end
300
+
301
+ def attach_firewall(client, vm_id, ruleset_id, wait: true, timeout: DEFAULT_WAIT_TIMEOUT)
302
+ waiter(client, timeout).retry_busy { client.vm_action(vm_id, "attach-firewall", { "rulesetId" => ruleset_id }) }
303
+ return client.get_virtual_machine(vm_id) unless wait
304
+
305
+ wait_idle(client, vm_id, "the firewall to be applied", timeout) { |vm| vm["firewallRulesetId"] == ruleset_id }
306
+ end
307
+
308
+ def detach_firewall(client, vm_id, ruleset_id, wait: true, timeout: DEFAULT_WAIT_TIMEOUT)
309
+ waiter(client, timeout).retry_busy { client.vm_action(vm_id, "detach-firewall", { "rulesetId" => ruleset_id }) }
310
+ return client.get_virtual_machine(vm_id) unless wait
311
+
312
+ wait_idle(client, vm_id, "the firewall to be removed", timeout) { |vm| vm["firewallRulesetId"].to_s.empty? }
313
+ end
314
+
315
+ # Reinstalls the operating system. This erases the disk; the IP addresses stay.
316
+ def reinstall(client, vm_id, hostname, distro, ssh_key_ids: [], password: nil, wait: true,
317
+ timeout: DEFAULT_WAIT_TIMEOUT)
318
+ body = { "hostname" => hostname.to_s, "distro" => distro_enum(distro) }
319
+ body["sshKeyIds"] = ssh_key_ids unless ssh_key_ids.empty?
320
+ body["password"] = password unless password.to_s.empty?
321
+ waiter(client, timeout).retry_busy { client.vm_action(vm_id, "reinstall", body) }
322
+ return client.get_virtual_machine(vm_id) unless wait
323
+
324
+ # The status may still read COMPLETED from an earlier reinstall for a moment.
325
+ client.sleep_for(3)
326
+ waiter(client, timeout).wait("the reinstall to finish") do
327
+ vm = client.get_virtual_machine(vm_id)
328
+ status = vm["reinstallStatus"]
329
+ raise UsageError, "the reinstall of virtual machine #{vm_id} failed; the API does not report why" if status == "REINSTALL_STATUS_FAILED"
330
+
331
+ [status == "REINSTALL_STATUS_COMPLETED" && vm["crStatus"] != "CR_STATUS_PROCESSING", vm]
332
+ end
333
+ wait_settled(client, vm_id, timeout)
334
+ end
335
+
336
+ # Orders a VM and returns it.
337
+ #
338
+ # Safe against lost responses: an ambiguous failure is retried with the
339
+ # same idempotency key, and free plans (which ignore the key) are tagged
340
+ # with a nonce so the VM is found instead of ordered twice.
341
+ def order_vm(client, hostname, plan_id, region_id, distro: nil, ssh_key_ids: [], password: nil,
342
+ tags: [], ruleset_id: nil, wait: true, timeout: DEFAULT_WAIT_TIMEOUT)
343
+ body = { "hostname" => hostname, "planId" => plan_id, "regionId" => region_id,
344
+ "idempotencyKey" => NoderingsVagrant.new_uuid }
345
+ body["distro"] = distro_enum(distro) unless distro.to_s.empty?
346
+ body["sshKeyIds"] = ssh_key_ids unless ssh_key_ids.empty?
347
+ body["password"] = password unless password.to_s.empty?
348
+ tags = Array(tags).uniq.sort
349
+
350
+ free = begin
351
+ client.get_marketplace_plan(plan_id)["billingType"] == "BILLING_TYPE_FREE"
352
+ rescue APIError
353
+ true
354
+ end
355
+ nonce = free ? NONCE_TAG_PREFIX + NoderingsVagrant.new_uuid : ""
356
+ tags += [nonce] unless nonce.empty?
357
+ body["tags"] = tags unless tags.empty?
358
+
359
+ find_by_nonce = -> { client.list_virtual_machines.find { |v| Array(v["tags"]).include?(nonce) } }
360
+
361
+ vm = nil
362
+ last_err = nil
363
+ new_key = false
364
+ 6.times do |attempt|
365
+ begin
366
+ vm = client.create_virtual_machine(body)
367
+ break
368
+ rescue APIError => e
369
+ last_err = e
370
+ if e.code == CODE_FAILED_PRECONDITION && e.api_message.downcase.include?("new idempotency key") && !new_key
371
+ new_key = true
372
+ body["idempotencyKey"] = NoderingsVagrant.new_uuid
373
+ next
374
+ end
375
+ raise UsageError, "ordering virtual machine #{hostname}: #{translate_create_error(e)}" unless e.ambiguous?
376
+ rescue *CONNECTION_ERRORS => e
377
+ last_err = e
378
+ end
379
+ unless nonce.empty?
380
+ vm = find_by_nonce.call
381
+ break if vm
382
+ end
383
+ client.sleep_for([2 * (attempt + 1), 10].min)
384
+ end
385
+ if vm.nil? && last_err
386
+ raise UsageError, "ordering virtual machine #{hostname}: #{last_err.message}. The order may or may " \
387
+ "not have been placed; check the console before trying again"
388
+ end
389
+ vm = find_by_nonce.call if (vm.nil? || vm["id"].to_s.empty?) && !nonce.empty?
390
+ if vm.nil? || vm["id"].to_s.empty?
391
+ raise UsageError, "the API accepted the order for #{hostname} but did not return the new virtual " \
392
+ "machine; check the console before trying again"
393
+ end
394
+
395
+ vm_id = vm["id"]
396
+ if wait || ruleset_id || !nonce.empty?
397
+ wait_provisioned(client, vm_id, timeout)
398
+ # The VM reads CREATED until the platform has booted it, then STARTED.
399
+ wait_settled(client, vm_id, timeout)
400
+ end
401
+ unless nonce.empty?
402
+ begin
403
+ client.update_virtual_machine_tags(vm_id, remove: [nonce])
404
+ rescue APIError
405
+ nil
406
+ end
407
+ end
408
+ attach_firewall(client, vm_id, ruleset_id, wait: wait, timeout: timeout) unless ruleset_id.to_s.empty?
409
+ client.get_virtual_machine(vm_id)
410
+ end
411
+ end
412
+ end
@@ -0,0 +1,98 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VagrantPlugins
4
+ module Noderings
5
+ # The `config.vm.provider :noderings` block.
6
+ class Config < Vagrant.plugin("2", :config)
7
+ TOKEN_ENV_VARS = %w[NODERINGS_TOKEN NODERINGS_API_TOKEN NR_API_TOKEN].freeze
8
+
9
+ # @return [String] NodeRings service account token (default: NODERINGS_TOKEN)
10
+ attr_accessor :token
11
+ # @return [String] API endpoint (default: NODERINGS_API_URL, then https://api.noderings.com)
12
+ attr_accessor :api_url
13
+ # @return [String] organization to act in, for tokens that reach several
14
+ attr_accessor :organization_id
15
+ # @return [String] plan code to order, such as SC-GC-1C-1G-20
16
+ attr_accessor :plan
17
+ # @return [String] country of the offer
18
+ attr_accessor :country
19
+ # @return [String] city of the offer
20
+ attr_accessor :city
21
+ # @return [String] usage, subscription or free
22
+ attr_accessor :billing_type
23
+ # @return [String] price (cheapest) or rating (best rated)
24
+ attr_accessor :sort
25
+ # @return [String] only consider offers from this provider
26
+ attr_accessor :provider_id
27
+ # @return [String] exact plan ID, instead of plan, country and city
28
+ attr_accessor :plan_id
29
+ # @return [String] exact region ID, with plan_id
30
+ attr_accessor :region_id
31
+ # @return [String] operating system, such as ubuntu_24_04
32
+ attr_accessor :distro
33
+ # @return [String] hostname of the server (default: vagrant-<machine>-<random>)
34
+ attr_accessor :hostname
35
+ # @return [Array<String>] existing NodeRings SSH key names or IDs; empty uploads a generated key
36
+ attr_accessor :ssh_keys
37
+ # @return [Array<String>] tags on the server
38
+ attr_accessor :tags
39
+ # @return [String] firewall ruleset name or ID to attach
40
+ attr_accessor :firewall_ruleset
41
+ # @return [Integer] seconds to wait for each operation
42
+ attr_accessor :wait_timeout
43
+
44
+ def initialize
45
+ super
46
+ @token = UNSET_VALUE
47
+ @api_url = UNSET_VALUE
48
+ @organization_id = UNSET_VALUE
49
+ @plan = UNSET_VALUE
50
+ @country = UNSET_VALUE
51
+ @city = UNSET_VALUE
52
+ @billing_type = UNSET_VALUE
53
+ @sort = UNSET_VALUE
54
+ @provider_id = UNSET_VALUE
55
+ @plan_id = UNSET_VALUE
56
+ @region_id = UNSET_VALUE
57
+ @distro = UNSET_VALUE
58
+ @hostname = UNSET_VALUE
59
+ @ssh_keys = UNSET_VALUE
60
+ @tags = UNSET_VALUE
61
+ @firewall_ruleset = UNSET_VALUE
62
+ @wait_timeout = UNSET_VALUE
63
+ end
64
+
65
+ def finalize!
66
+ @token = TOKEN_ENV_VARS.map { |v| ENV.fetch(v, nil) }.find { |v| !v.to_s.empty? } if @token == UNSET_VALUE
67
+ @api_url = ENV.fetch("NODERINGS_API_URL", nil) if @api_url == UNSET_VALUE
68
+ @organization_id = ENV.fetch("NODERINGS_ORGANIZATION_ID", nil) if @organization_id == UNSET_VALUE
69
+ @billing_type = "usage" if @billing_type == UNSET_VALUE
70
+ @sort = "price" if @sort == UNSET_VALUE
71
+ @distro = "ubuntu_24_04" if @distro == UNSET_VALUE
72
+ @ssh_keys = [] if @ssh_keys == UNSET_VALUE
73
+ @tags = ["vagrant"] if @tags == UNSET_VALUE
74
+ @wait_timeout = 900 if @wait_timeout == UNSET_VALUE
75
+ %i[plan country city provider_id plan_id region_id hostname firewall_ruleset].each do |name|
76
+ instance_variable_set("@#{name}", nil) if instance_variable_get("@#{name}") == UNSET_VALUE
77
+ end
78
+ @ssh_keys = Array(@ssh_keys)
79
+ @tags = Array(@tags)
80
+ @wait_timeout = Integer(@wait_timeout)
81
+ end
82
+
83
+ def validate(_machine)
84
+ errors = _detected_errors
85
+ errors << "token is required: set provider.token or the NODERINGS_TOKEN environment variable" if @token.to_s.empty?
86
+ unless (@plan_id && @region_id) || (@plan && @country && @city)
87
+ errors << "set plan, country and city (or plan_id and region_id) to choose what to order"
88
+ end
89
+ errors << "billing_type must be usage, subscription or free" unless %w[usage subscription free].include?(@billing_type.to_s)
90
+ errors << "sort must be price or rating" unless %w[price rating].include?(@sort.to_s)
91
+ if @hostname && @hostname !~ /\A[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\z/
92
+ errors << "hostname must be one DNS label: letters, digits and hyphens, at most 63 characters"
93
+ end
94
+ { "NodeRings provider" => errors }
95
+ end
96
+ end
97
+ end
98
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VagrantPlugins
4
+ module Noderings
5
+ module Errors
6
+ class NoderingsError < Vagrant::Errors::VagrantError
7
+ error_namespace("vagrant_noderings.errors")
8
+ end
9
+
10
+ # Any failure from the NodeRings API, with its message.
11
+ class APIError < NoderingsError
12
+ error_key(:api_error)
13
+ end
14
+
15
+ class NoAddress < NoderingsError
16
+ error_key(:no_address)
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,53 @@
1
+ # frozen_string_literal: true
2
+
3
+ begin
4
+ require "vagrant"
5
+ rescue LoadError
6
+ raise "The NodeRings provider must be run within Vagrant."
7
+ end
8
+
9
+ raise "The NodeRings provider needs Vagrant 2.2 or later." if Gem::Version.new(Vagrant::VERSION) < Gem::Version.new("2.2.0")
10
+
11
+ module VagrantPlugins
12
+ module Noderings
13
+ class Plugin < Vagrant.plugin("2")
14
+ name "NodeRings"
15
+ description <<~DESC
16
+ A Vagrant provider that runs machines on NodeRings virtual machines, ordered
17
+ from the NodeRings marketplace.
18
+ DESC
19
+
20
+ config(:noderings, :provider) do
21
+ require_relative "config"
22
+ Config
23
+ end
24
+
25
+ # No box is needed: the operating system comes from the provider config.
26
+ provider(:noderings, parallel: true, box_optional: true) do
27
+ setup_i18n
28
+ setup_logging
29
+ require_relative "provider"
30
+ Provider
31
+ end
32
+
33
+ def self.setup_i18n
34
+ I18n.load_path << File.expand_path("locales/en.yml", Noderings.source_root)
35
+ I18n.reload!
36
+ end
37
+
38
+ def self.setup_logging
39
+ require "log4r"
40
+ level = begin
41
+ Log4r.const_get(ENV.fetch("VAGRANT_LOG", "").upcase)
42
+ rescue NameError
43
+ nil
44
+ end
45
+ return unless level.is_a?(Integer)
46
+
47
+ logger = Log4r::Logger.new("vagrant_noderings") # registered globally by name
48
+ logger.outputters = Log4r::Outputter.stderr
49
+ logger.level = level # rubocop:disable Lint/UselessSetterCall
50
+ end
51
+ end
52
+ end
53
+ end
@@ -0,0 +1,37 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "log4r"
4
+ require "vagrant"
5
+
6
+ module VagrantPlugins
7
+ module Noderings
8
+ class Provider < Vagrant.plugin("2", :provider)
9
+ def initialize(machine)
10
+ super
11
+ @machine = machine
12
+ # The server is remote: sync folders with rsync, not NFS or SMB.
13
+ @machine.config.nfs.functional = false
14
+ @machine.config.smb.functional = false
15
+ end
16
+
17
+ def action(name)
18
+ method = "action_#{name}"
19
+ Action.respond_to?(method) ? Action.send(method) : nil
20
+ end
21
+
22
+ def ssh_info
23
+ @machine.action("read_ssh_info")[:machine_ssh_info]
24
+ end
25
+
26
+ def state
27
+ id = @machine.action("read_state")[:machine_state_id]
28
+ Vagrant::MachineState.new(id, I18n.t("vagrant_noderings.states.short_#{id}", default: id.to_s),
29
+ I18n.t("vagrant_noderings.states.long_#{id}", default: id.to_s))
30
+ end
31
+
32
+ def to_s
33
+ "NodeRings (#{@machine.id || 'new'})"
34
+ end
35
+ end
36
+ end
37
+ end