Class: VagrantPlugins::DigitalOcean::Helpers::ApiClient

Inherits:
Object
  • Object
show all
Includes:
Vagrant::Util::Retryable
Defined in:
lib/vagrant-digitalocean/helpers/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(env) ⇒ ApiClient

Returns a new instance of ApiClient.



17
18
19
20
21
22
23
24
25
26
# File 'lib/vagrant-digitalocean/helpers/client.rb', line 17

def initialize(env)
  @env = env
  @config = env[:machine].provider_config
  @client = Faraday.new({
    :url => "https://api.digitalocean.com/",
    :ssl => {
      :ca_file => @config.ca_path
    }
  })
end

Instance Method Details

#request(path, params = {}) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/vagrant-digitalocean/helpers/client.rb', line 28

def request(path, params = {})
  begin
    result = @client.get(path, params = params.merge({
      :client_id => @config.client_id,
      :api_key => @config.api_key
    }))
  rescue Faraday::Error::ConnectionFailed => e
    # TODO this is suspect but because farady wraps the exception
    #      in something generic there doesn't appear to be another
    #      way to distinguish different connection errors :(
    if e.message =~ /certificate verify failed/
      raise Errors::CertificateError
    end

    raise e
  end

  # remove the api key in case an error gets dumped to the console
  params[:api_key] = "REMOVED"

  begin
    body = JSON.parse(result.body)
  rescue JSON::ParserError => e
    raise(Errors::JSONError, {
      :message => e.message,
      :path => path,
      :params => params,
      :response => result.body
    })
  end

  if body["status"] != "OK"
    raise(Errors::APIStatusError, {
      :path => path,
      :params => params,
      :status => body["status"],
      :response => body.inspect
    })
  end

  Result.new(body)
end

#wait_for_event(id) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/vagrant-digitalocean/helpers/client.rb', line 71

def wait_for_event(id)
  retryable(:tries => 30, :sleep => 10) do
    # stop waiting if interrupted
    next if @env[:interrupted]


    # check event status
    result = self.request("/events/#{id}")

    yield result if block_given?
    raise "not ready" if result["event"]["action_status"] != "done"
  end
end