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,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module VagrantPlugins
4
+ module Noderings
5
+ module Action
6
+ # Waits until SSH answers. A new server opens port 22 before cloud-init has
7
+ # installed the key, so this retries until a login works.
8
+ module WaitForCommunicator
9
+ def self.wait(env, timeout)
10
+ machine = env[:machine]
11
+ env[:ui].info(I18n.t("vagrant_noderings.waiting_for_ssh"))
12
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
13
+ until machine.communicate.ready?
14
+ if Process.clock_gettime(Process::CLOCK_MONOTONIC) > deadline
15
+ raise Errors::APIError, action: "waiting for SSH",
16
+ message: "the server did not answer SSH in time"
17
+ end
18
+ return if env[:interrupted]
19
+
20
+ sleep(Session.sleeper ? 0 : 5)
21
+ end
22
+ env[:ui].info(I18n.t("vagrant_noderings.ready"))
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "pathname"
4
+ require "vagrant/action/builder"
5
+
6
+ module VagrantPlugins
7
+ module Noderings
8
+ # The middleware stacks behind each Vagrant command.
9
+ module Action
10
+ include Vagrant::Action::Builtin
11
+
12
+ def self.action_up
13
+ Vagrant::Action::Builder.new.tap do |b|
14
+ b.use HandleBox
15
+ b.use ConfigValidate
16
+ b.use Call, IsCreated do |env, b1|
17
+ if env[:result]
18
+ b1.use Call, IsStopped do |env2, b2|
19
+ if env2[:result]
20
+ b2.use Provision
21
+ b2.use SyncedFolders
22
+ b2.use StartServer
23
+ else
24
+ b2.use Message, I18n.t("vagrant_noderings.already_created")
25
+ end
26
+ end
27
+ else
28
+ b1.use Provision
29
+ b1.use SyncedFolders
30
+ b1.use CreateServer
31
+ end
32
+ end
33
+ end
34
+ end
35
+
36
+ def self.action_halt
37
+ Vagrant::Action::Builder.new.tap do |b|
38
+ b.use ConfigValidate
39
+ b.use Call, IsCreated do |env, b1|
40
+ if env[:result]
41
+ b1.use StopServer
42
+ else
43
+ b1.use Message, I18n.t("vagrant_noderings.not_created")
44
+ end
45
+ end
46
+ end
47
+ end
48
+
49
+ def self.action_destroy
50
+ Vagrant::Action::Builder.new.tap do |b|
51
+ b.use Call, DestroyConfirm do |env, b1|
52
+ if env[:result]
53
+ b1.use ConfigValidate
54
+ b1.use Call, IsCreated do |env2, b2|
55
+ if env2[:result]
56
+ b2.use DestroyServer
57
+ else
58
+ b2.use Message, I18n.t("vagrant_noderings.not_created")
59
+ b2.use CleanupFiles
60
+ end
61
+ end
62
+ else
63
+ b1.use Message, I18n.t("vagrant_noderings.will_not_destroy", name: env[:machine].name)
64
+ end
65
+ end
66
+ end
67
+ end
68
+
69
+ def self.action_reload
70
+ Vagrant::Action::Builder.new.tap do |b|
71
+ b.use ConfigValidate
72
+ b.use Call, IsCreated do |env, b1|
73
+ if env[:result]
74
+ b1.use action_halt
75
+ b1.use action_up
76
+ else
77
+ b1.use Message, I18n.t("vagrant_noderings.not_created")
78
+ end
79
+ end
80
+ end
81
+ end
82
+
83
+ def self.action_provision
84
+ Vagrant::Action::Builder.new.tap do |b|
85
+ b.use ConfigValidate
86
+ b.use Call, IsCreated do |env, b1|
87
+ if env[:result]
88
+ b1.use Provision
89
+ b1.use SyncedFolders
90
+ else
91
+ b1.use Message, I18n.t("vagrant_noderings.not_created")
92
+ end
93
+ end
94
+ end
95
+ end
96
+
97
+ def self.action_ssh
98
+ running_only(SSHExec)
99
+ end
100
+
101
+ def self.action_ssh_run
102
+ running_only(SSHRun)
103
+ end
104
+
105
+ def self.running_only(middleware)
106
+ Vagrant::Action::Builder.new.tap do |b|
107
+ b.use ConfigValidate
108
+ b.use Call, IsCreated do |env, b1|
109
+ if env[:result]
110
+ b1.use middleware
111
+ else
112
+ b1.use Message, I18n.t("vagrant_noderings.not_created")
113
+ end
114
+ end
115
+ end
116
+ end
117
+
118
+ def self.action_read_ssh_info
119
+ Vagrant::Action::Builder.new.tap { |b| b.use ReadSSHInfo }
120
+ end
121
+
122
+ def self.action_read_state
123
+ Vagrant::Action::Builder.new.tap { |b| b.use ReadState }
124
+ end
125
+
126
+ root = Pathname.new(File.expand_path("action", __dir__))
127
+ autoload :CleanupFiles, root.join("cleanup_files")
128
+ autoload :CreateServer, root.join("create_server")
129
+ autoload :DestroyServer, root.join("destroy_server")
130
+ autoload :IsCreated, root.join("is_created")
131
+ autoload :IsStopped, root.join("is_stopped")
132
+ autoload :ReadSSHInfo, root.join("read_ssh_info")
133
+ autoload :ReadState, root.join("read_state")
134
+ autoload :StartServer, root.join("start_server")
135
+ autoload :StopServer, root.join("stop_server")
136
+ autoload :WaitForCommunicator, root.join("wait_for_communicator")
137
+ end
138
+ end
139
+ end
@@ -0,0 +1,521 @@
1
+ # frozen_string_literal: true
2
+
3
+ #
4
+ # Copyright:: NodeRings
5
+ # License:: Apache-2.0
6
+ #
7
+ # A small JSON client for the NodeRings public API, written against the Ruby
8
+ # standard library only so the cookbook installs no gems on the node.
9
+
10
+ require "json" unless defined?(JSON)
11
+ require "net/http" unless defined?(Net::HTTP)
12
+ require "openssl" unless defined?(OpenSSL)
13
+ require "securerandom" unless defined?(SecureRandom)
14
+ require "uri" unless defined?(URI)
15
+
16
+ module NoderingsVagrant
17
+ DEFAULT_API_URL = "https://api.noderings.com"
18
+ TOKEN_ENV_VARS = %w{NODERINGS_TOKEN NODERINGS_API_TOKEN NR_API_TOKEN}.freeze
19
+
20
+ # gRPC status codes carried in the API's error bodies.
21
+ CODE_INVALID_ARGUMENT = 3
22
+ CODE_NOT_FOUND = 5
23
+ CODE_ALREADY_EXISTS = 6
24
+ CODE_PERMISSION_DENIED = 7
25
+ CODE_FAILED_PRECONDITION = 9
26
+ CODE_UNAUTHENTICATED = 16
27
+
28
+ UUID_RE = /\A\h{8}-\h{4}-\h{4}-\h{4}-\h{12}\z/
29
+
30
+ # Network failures that may or may not have reached the API.
31
+ CONNECTION_ERRORS = [
32
+ SocketError, IOError, EOFError, SystemCallError, Timeout::Error,
33
+ Net::OpenTimeout, Net::ReadTimeout, OpenSSL::SSL::SSLError
34
+ ].freeze
35
+
36
+ # An error the NodeRings API returned.
37
+ class APIError < StandardError
38
+ attr_reader :status, :code, :api_message, :details, :http_method, :path
39
+
40
+ def initialize(status, code = 0, message = "", details = nil, http_method = "", path = "")
41
+ @status = status
42
+ @code = code
43
+ @api_message = message.to_s.strip
44
+ @details = details || []
45
+ @http_method = http_method
46
+ @path = path
47
+ super(build_message)
48
+ end
49
+
50
+ def quota_info
51
+ @details.find do |d|
52
+ d.is_a?(Hash) && d["@type"].to_s.end_with?("google.rpc.ErrorInfo") &&
53
+ d["reason"].to_s.end_with?("LIMIT_REACHED")
54
+ end
55
+ end
56
+
57
+ def quota?
58
+ !quota_info.nil?
59
+ end
60
+
61
+ def not_found?
62
+ @code == CODE_NOT_FOUND
63
+ end
64
+
65
+ # The API refuses changes while a VM operation is running.
66
+ def busy?
67
+ @code == CODE_FAILED_PRECONDITION && @api_message.downcase.include?("in progress")
68
+ end
69
+
70
+ # True when the request may or may not have been applied (lost response).
71
+ def ambiguous?
72
+ return true if [502, 503, 504].include?(@status)
73
+ return !quota? if @status == 429
74
+
75
+ false
76
+ end
77
+
78
+ private
79
+
80
+ def build_message
81
+ msg = @api_message.empty? ? "HTTP #{@status}" : @api_message
82
+ meta = (quota_info || {})["metadata"] || {}
83
+ return "#{msg} (quota #{meta["limit_key"]}: #{meta["current"]} of #{meta["limit"]} used)" if meta.key?("limit")
84
+
85
+ where = @http_method.to_s.empty? ? "" : " on #{@http_method} #{@path}"
86
+ "#{msg} (HTTP #{@status}#{where})"
87
+ end
88
+ end
89
+
90
+ # A wait ran out of time.
91
+ class WaitTimeout < StandardError; end
92
+
93
+ # The caller asked for something that cannot work (bad name, ambiguous match, no offer).
94
+ class UsageError < StandardError; end
95
+
96
+ module_function
97
+
98
+ def decode_error(status, body, http_method = "", path = "")
99
+ code = 0
100
+ message = ""
101
+ details = []
102
+ begin
103
+ data = JSON.parse(body.to_s.empty? ? "{}" : body.to_s)
104
+ if data.is_a?(Hash)
105
+ code = data["code"].to_i
106
+ message = data["message"].to_s
107
+ details = data["details"] || []
108
+ else
109
+ message = data.to_s[0, 300]
110
+ end
111
+ rescue JSON::ParserError
112
+ message = body.to_s.strip[0, 300]
113
+ end
114
+ if code == 0
115
+ code = { 404 => CODE_NOT_FOUND, 409 => CODE_ALREADY_EXISTS, 403 => CODE_PERMISSION_DENIED,
116
+ 401 => CODE_UNAUTHENTICATED }.fetch(status, 0)
117
+ end
118
+ APIError.new(status, code, message, details, http_method, path)
119
+ end
120
+
121
+ def ambiguous?(err)
122
+ return err.ambiguous? if err.is_a?(APIError)
123
+
124
+ CONNECTION_ERRORS.any? { |k| err.is_a?(k) }
125
+ end
126
+
127
+ def not_found?(err)
128
+ err.is_a?(APIError) && err.not_found?
129
+ end
130
+
131
+ def uuid?(value)
132
+ UUID_RE.match?(value.to_s)
133
+ end
134
+
135
+ def new_uuid
136
+ SecureRandom.uuid
137
+ end
138
+
139
+ def escape(value)
140
+ URI.encode_www_form_component(value.to_s).gsub("+", "%20")
141
+ end
142
+
143
+ # BILLING_TYPE_USAGE -> usage
144
+ def trim_enum(value, prefix)
145
+ return "" if value.nil? || value.to_s.empty?
146
+
147
+ v = value.to_s.delete_prefix(prefix)
148
+ v == "UNSPECIFIED" ? "" : v.downcase
149
+ end
150
+
151
+ def find_by_name(items, name)
152
+ Array(items).find { |i| i["name"] == name }
153
+ end
154
+
155
+ # Sends requests over Net::HTTP. Returns [status, body].
156
+ class NetHTTPTransport
157
+ def call(http_method, url, headers, body, timeout)
158
+ uri = URI(url)
159
+ http = Net::HTTP.new(uri.host, uri.port)
160
+ http.use_ssl = uri.scheme == "https"
161
+ http.open_timeout = [timeout, 30].min
162
+ http.read_timeout = timeout
163
+ req = Net::HTTPGenericRequest.new(http_method, !body.nil?, true, uri.request_uri, headers)
164
+ req.body = body if body
165
+ res = http.start { |h| h.request(req) }
166
+ [res.code.to_i, res.body.to_s]
167
+ end
168
+ end
169
+
170
+ # JSON client for the NodeRings public API.
171
+ class Client
172
+ attr_reader :base, :organization_id, :user_agent
173
+
174
+ def initialize(token:, api_url: nil, organization_id: nil, timeout: 60, retries: 5,
175
+ user_agent: nil, transport: nil, sleeper: nil)
176
+ if token.nil? || token.to_s.strip.empty?
177
+ raise UsageError, "A NodeRings API token is required. Set provider.token in the Vagrantfile, or the " \
178
+ "NODERINGS_TOKEN environment variable. Create a service account token in the NodeRings " \
179
+ "console under Organization, Access Control, Service accounts."
180
+ end
181
+ @base = (api_url.to_s.empty? ? DEFAULT_API_URL : api_url.to_s).chomp("/")
182
+ raise UsageError, "api_url must be an absolute URL such as #{DEFAULT_API_URL}" unless @base.start_with?("https://", "http://")
183
+
184
+ @token = token.to_s.strip
185
+ @organization_id = organization_id.to_s.strip
186
+ @timeout = Integer(timeout)
187
+ @retries = [0, Integer(retries)].max
188
+ @user_agent = user_agent || "noderings-ruby"
189
+ @transport = transport || NetHTTPTransport.new
190
+ @sleeper = sleeper || ->(s) { sleep(s) }
191
+ end
192
+
193
+ # Keep the token out of inspect output and logs.
194
+ def inspect
195
+ "#<#{self.class.name} base=#{@base}>"
196
+ end
197
+
198
+ def sleep_for(seconds)
199
+ @sleeper.call(seconds)
200
+ end
201
+
202
+ # Sends one request and returns the decoded JSON body, or {}.
203
+ #
204
+ # GET requests retry on 503; writes do not, because some write endpoints
205
+ # (DNS) report validation errors as 503.
206
+ def request(http_method, path, query: nil, body: nil, retry_unavailable: nil, retries: nil)
207
+ retry_unavailable = (http_method == "GET") if retry_unavailable.nil?
208
+ max_retries = retries.nil? ? @retries : retries
209
+ url = @base + path
210
+ qs = encode_query(query)
211
+ url += "?#{qs}" unless qs.empty?
212
+ headers = {
213
+ "Authorization" => "Bearer #{@token}",
214
+ "Accept" => "application/json",
215
+ "User-Agent" => @user_agent,
216
+ }
217
+ payload = nil
218
+ unless body.nil?
219
+ payload = JSON.generate(body)
220
+ headers["Content-Type"] = "application/json"
221
+ end
222
+ headers["X-Organization-ID"] = @organization_id unless @organization_id.empty?
223
+
224
+ attempt = 0
225
+ loop do
226
+ err = nil
227
+ begin
228
+ status, raw = @transport.call(http_method, url, headers, payload, @timeout)
229
+ if status < 300
230
+ return {} if raw.nil? || raw.strip.empty?
231
+
232
+ return JSON.parse(raw)
233
+ end
234
+ err = NoderingsVagrant.decode_error(status, raw, http_method, path)
235
+ rescue *CONNECTION_ERRORS => e
236
+ err = e
237
+ end
238
+ raise err if attempt >= max_retries || !retryable?(err, retry_unavailable)
239
+
240
+ sleep_for(backoff(attempt))
241
+ attempt += 1
242
+ end
243
+ end
244
+
245
+ def get(path, query = nil)
246
+ request("GET", path, query: query)
247
+ end
248
+
249
+ def list_all(path, key, query = {})
250
+ get(path, { "page" => "0", "pageSize" => "-1" }.merge(query))[key] || []
251
+ end
252
+
253
+ def list_paged(path, key, query = {}, page_size = 100)
254
+ out = []
255
+ page = 0
256
+ loop do
257
+ data = get(path, { "page" => page.to_s, "pageSize" => page_size.to_s }.merge(query))
258
+ items = data[key] || []
259
+ out.concat(items)
260
+ return out if items.length < page_size || out.length >= data["totalCount"].to_i
261
+
262
+ page += 1
263
+ end
264
+ end
265
+
266
+ # -- organization -----------------------------------------------------------
267
+
268
+ def organization
269
+ get("/v1/organization")["organization"]
270
+ end
271
+
272
+ def credit_balance
273
+ get("/v1/credits/balance")
274
+ end
275
+
276
+ # -- SSH keys -----------------------------------------------------------------
277
+
278
+ def list_ssh_keys
279
+ list_all("/v1/ssh-keys", "sshKeys")
280
+ end
281
+
282
+ def create_ssh_key(name, public_key)
283
+ request("POST", "/v1/ssh-keys", body: { "name" => name, "publicKey" => public_key })["sshKey"]
284
+ end
285
+
286
+ def delete_ssh_key(key_id)
287
+ request("DELETE", "/v1/ssh-keys/#{NoderingsVagrant.escape(key_id)}")
288
+ end
289
+
290
+ # -- DNS ----------------------------------------------------------------------
291
+
292
+ def zone_path(zone_id)
293
+ "/v1/dns/zones/#{NoderingsVagrant.escape(zone_id)}"
294
+ end
295
+
296
+ def list_dns_zones
297
+ list_all("/v1/dns/zones", "zones")
298
+ end
299
+
300
+ def get_dns_zone(zone_id)
301
+ get(zone_path(zone_id))["zone"]
302
+ end
303
+
304
+ def create_dns_zone(name)
305
+ request("POST", "/v1/dns/zones", body: { "name" => name })["zone"]
306
+ end
307
+
308
+ def delete_dns_zone(zone_id, force: false)
309
+ request("DELETE", zone_path(zone_id), query: force ? { "force" => "true" } : nil)
310
+ end
311
+
312
+ def list_dns_records(zone_id, name: nil, type: nil)
313
+ list_paged("#{zone_path(zone_id)}/records", "records", { "name" => name, "type" => type })
314
+ end
315
+
316
+ def upsert_dns_record(zone_id, record)
317
+ request("PUT", "#{zone_path(zone_id)}/records", body: { "record" => record })
318
+ end
319
+
320
+ def delete_dns_record(zone_id, name, type)
321
+ request("DELETE", "#{zone_path(zone_id)}/records", query: { "name" => name, "type" => type })
322
+ end
323
+
324
+ def get_dnssec(zone_id)
325
+ get("#{zone_path(zone_id)}/dnssec")
326
+ end
327
+
328
+ def enable_dnssec(zone_id)
329
+ request("POST", "#{zone_path(zone_id)}/dnssec/enable", body: {})
330
+ end
331
+
332
+ def disable_dnssec(zone_id, force: false)
333
+ request("POST", "#{zone_path(zone_id)}/dnssec/disable", body: { "force" => force })
334
+ end
335
+
336
+ # -- firewall -----------------------------------------------------------------
337
+
338
+ def list_firewall_address_groups(name = nil)
339
+ list_all("/v1/firewall/address-groups", "groups", { "name" => name })
340
+ end
341
+
342
+ def list_firewall_rulesets(name = nil)
343
+ list_all("/v1/firewall/rulesets", "rulesets", { "name" => name })
344
+ end
345
+
346
+ def create_firewall_ruleset(name)
347
+ out = request("POST", "/v1/firewall/rulesets", body: { "ruleset" => { "name" => name } })["ruleset"]
348
+ return out if out && out["id"]
349
+
350
+ NoderingsVagrant.find_by_name(list_firewall_rulesets(name), name)
351
+ end
352
+
353
+ def delete_firewall_ruleset(ruleset_id, force: false)
354
+ request("DELETE", "/v1/firewall/rulesets/#{NoderingsVagrant.escape(ruleset_id)}",
355
+ query: force ? { "force" => "true" } : nil)
356
+ end
357
+
358
+ def list_firewall_rules(ruleset_id)
359
+ list_all("/v1/firewall/rulesets/#{NoderingsVagrant.escape(ruleset_id)}/rules", "rules")
360
+ .sort_by { |r| r["position"].to_i }
361
+ end
362
+
363
+ def create_firewall_rule(ruleset_id, rule)
364
+ request("POST", "/v1/firewall/rulesets/#{NoderingsVagrant.escape(ruleset_id)}/rules",
365
+ body: { "rule" => rule })["rule"]
366
+ end
367
+
368
+ def update_firewall_rule(rule_id, rule)
369
+ request("PATCH", "/v1/firewall/rules/#{NoderingsVagrant.escape(rule_id)}", body: { "rule" => rule })
370
+ end
371
+
372
+ def move_firewall_rule(rule_id, target_id, position = "FIREWALL_RULE_POSITION_BEFORE")
373
+ request("POST", "/v1/firewall/rules/#{NoderingsVagrant.escape(rule_id)}/move",
374
+ body: { "targetRuleId" => target_id, "position" => position })
375
+ end
376
+
377
+ def delete_firewall_rule(rule_id)
378
+ request("DELETE", "/v1/firewall/rules/#{NoderingsVagrant.escape(rule_id)}")
379
+ end
380
+
381
+ # -- virtual machines ---------------------------------------------------------
382
+
383
+ def vm_path(vm_id)
384
+ "/v1/virtual-machines/#{NoderingsVagrant.escape(vm_id)}"
385
+ end
386
+
387
+ def list_virtual_machines
388
+ list_all("/v1/virtual-machines", "virtualMachines")
389
+ end
390
+
391
+ def get_virtual_machine(vm_id)
392
+ vm = get(vm_path(vm_id))
393
+ raise APIError.new(404, CODE_NOT_FOUND, "virtual machine #{vm_id} not found") if vm.nil? || vm["id"].to_s.empty?
394
+
395
+ vm
396
+ end
397
+
398
+ # Never retried blindly: the caller handles ambiguous failures.
399
+ def create_virtual_machine(body)
400
+ request("POST", "/v1/virtual-machines", body: body, retries: 0)["virtualMachine"]
401
+ end
402
+
403
+ def update_virtual_machine_tags(vm_id, add: [], remove: [])
404
+ request("PATCH", vm_path(vm_id), body: { "addTags" => add, "removeTags" => remove })
405
+ end
406
+
407
+ def delete_virtual_machine(vm_id)
408
+ request("DELETE", vm_path(vm_id))
409
+ end
410
+
411
+ def vm_action(vm_id, action, body = {})
412
+ request("POST", "#{vm_path(vm_id)}:#{action}", body: body)
413
+ end
414
+
415
+ # -- marketplace and catalog --------------------------------------------------
416
+
417
+ def list_marketplace_regions(asset_type = nil)
418
+ get("/v1/marketplace/regions", { "filterAssetType" => asset_type })["regions"] || []
419
+ end
420
+
421
+ def list_available_plans(country: nil, city: nil, billing_type: nil, asset_type: nil)
422
+ get("/v1/marketplace/plans", {
423
+ "filterCountry" => country, "filterCity" => city,
424
+ "filterBillingType" => billing_type, "filterAssetType" => asset_type
425
+ })["plans"] || []
426
+ end
427
+
428
+ def get_marketplace_plan(plan_id)
429
+ get("/v1/marketplace/plans/#{NoderingsVagrant.escape(plan_id)}")
430
+ end
431
+
432
+ def list_providers(plan_code, country, city, billing_type: nil, ipv6_only: false)
433
+ query = {
434
+ "page" => "0", "pageSize" => "-1", "filterPlanCode" => plan_code,
435
+ "filterCountry" => country, "filterCity" => city, "filterBillingType" => billing_type
436
+ }
437
+ query["filterIpv6AvailableOnly"] = "true" if ipv6_only
438
+ get("/v1/marketplace/providers", query)["providers"] || []
439
+ end
440
+
441
+ def get_provider(provider_id)
442
+ get("/v1/marketplace/providers/#{NoderingsVagrant.escape(provider_id)}")["provider"]
443
+ end
444
+
445
+ def list_distros
446
+ get("/v1/distros")["distros"] || []
447
+ end
448
+
449
+ private
450
+
451
+ def encode_query(query)
452
+ return "" if query.nil?
453
+
454
+ pairs = []
455
+ query.keys.sort.each do |key|
456
+ value = query[key]
457
+ next if value.nil? || value == ""
458
+
459
+ case value
460
+ when Array then value.each { |v| pairs << [key, v.to_s] }
461
+ when true, false then pairs << [key, value ? "true" : "false"]
462
+ else pairs << [key, value.to_s]
463
+ end
464
+ end
465
+ URI.encode_www_form(pairs)
466
+ end
467
+
468
+ def backoff(attempt)
469
+ delay = [0.5 * (2**[attempt, 10].min), 10.0].min
470
+ (delay / 2) + (rand * delay / 2)
471
+ end
472
+
473
+ def retryable?(err, retry_unavailable)
474
+ return true unless err.is_a?(APIError)
475
+ return !err.quota? if err.status == 429
476
+ return true if [502, 504].include?(err.status)
477
+ return retry_unavailable if err.status == 503
478
+
479
+ false
480
+ end
481
+ end
482
+
483
+ # Polls with a growing interval until a check reports done or a timeout passes.
484
+ class Waiter
485
+ def initialize(timeout, sleeper:, interval: 2.0, max_interval: 15.0, clock: nil)
486
+ @clock = clock || -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
487
+ @deadline = @clock.call + timeout
488
+ @interval = interval
489
+ @max_interval = max_interval
490
+ @sleeper = sleeper
491
+ end
492
+
493
+ # The block returns [done, value].
494
+ def wait(what)
495
+ delay = @interval
496
+ loop do
497
+ done, value = yield
498
+ return value if done
499
+ raise WaitTimeout, "timed out waiting for #{what}" if @clock.call + delay > @deadline
500
+
501
+ @sleeper.call(delay)
502
+ delay = [delay * 1.5, @max_interval].min
503
+ end
504
+ end
505
+
506
+ # Runs the block until the VM stops reporting 'operation in progress'.
507
+ def retry_busy
508
+ last = nil
509
+ wait("the virtual machine to finish its current operation") do
510
+ [true, yield]
511
+ rescue APIError => e
512
+ raise unless e.busy?
513
+
514
+ last = e
515
+ [false, nil]
516
+ end
517
+ rescue WaitTimeout => e
518
+ raise WaitTimeout, "#{e.message} (last error: #{last})"
519
+ end
520
+ end
521
+ end