Class: VagrantPlugins::OneCloud::Helpers::ApiClient

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

Instance Method Summary collapse

Constructor Details

#initialize(machine) ⇒ ApiClient

Returns a new instance of ApiClient.



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

def initialize(machine)
  @logger = Log4r::Logger.new('vagrant::onecloud::apiclient')
  @config = machine.provider_config
  @machine = machine
  @client = Faraday.new({
    :url => @config.api_url,
    :ssl => {
      :ca_file => @config.ca_path
    }
  })
end

Instance Method Details

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



29
30
31
32
# File 'lib/vagrant-1cloud/helpers/client.rb', line 29

def delete(path, params = {})
  @client.request :url_encoded
  request(path, params, :delete)
end

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



34
35
36
37
# File 'lib/vagrant-1cloud/helpers/client.rb', line 34

def post(path, params = {})
  @client.headers['Content-Type'] = 'application/json'
  request(path, params, :post)
end

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



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
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/vagrant-1cloud/helpers/client.rb', line 39

def request(path, params = {}, method = :get)
  begin
    @logger.info "Request: #{path}"
    @logger.info "Parameters: #{params}"
    result = @client.send(method) do |req|
      req.url path
      req.headers['Authorization'] = "Bearer #{@config.token}"
      req.body = params.to_json
    end
  rescue Faraday::Error::ConnectionFailed => e
    # TODO this is suspect but because faraday 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

  unless method == :delete
    begin
      body = JSON.parse(%Q[{"body":#{result.body}}])
      @logger.info "Response: #{body}"
    rescue JSON::ParserError => e
      raise(Errors::JSONError, {
        :message => e.message,
        :path => path,
        :params => params,
        :response => result.body
      })
    end
  end

  unless /^2\d\d$/ =~ result.status.to_s
    raise(Errors::APIStatusError, {
      :path => path,
      :params => params,
      :status => result.status,
      :response => body.inspect
    })
  end

  Result.new(body)
end

#wait_for_destroy(env, id) ⇒ Object



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/vagrant-1cloud/helpers/client.rb', line 97

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

    # check action status
    begin
      result = @client.send(:get) do |req|
        req.url "/server/#{id}"
        req.headers['Authorization'] = "Bearer #{@config.token}"
      end
    rescue Faraday::Error::ConnectionFailed => e
      # TODO this is suspect but because faraday 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
    begin
      body = JSON.parse(%Q[{"body":#{result.body}}])
      @logger.info "Response: #{body}"
    rescue JSON::ParserError => e
      raise(Errors::JSONError, {
          :message => e.message,
          :path => path,
          :params => params,
          :response => result.body
      })
    end
    result = Result.new(body)
    yield result if block_given?
    raise 'Destroy is not completed' if result['body']['Message'] != 'Server not found'
  end
end

#wait_for_event(env, m_id, id) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/vagrant-1cloud/helpers/client.rb', line 84

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

    # check action status
    result = self.request("/server/#{m_id}/action/#{id}")

    yield result if block_given?
    raise 'Action is not completed' if result['body']['State'] != 'Completed'
  end
end

#wait_for_network(env, net_id) ⇒ Object



134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/vagrant-1cloud/helpers/client.rb', line 134

def wait_for_network(env, net_id)
  retryable(:tries => 400, :sleep => 10) do
    # stop waiting if interrupted
    next if env[:interrupted]

    # check network status
    result = self.request("/network/#{net_id}")

    yield result if block_given?
    raise 'Network is not active' if result['body']['State'] != 'Active'
  end
end

#wait_for_ssh(env, reboot_num, check_num) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/vagrant-1cloud/helpers/client.rb', line 147

def wait_for_ssh(env, reboot_num, check_num)
  i = 0
  while i <= reboot_num do
    j = 0
    while !@machine.communicate.ready? && j < check_num do
      env[:ui].info I18n.t('vagrant_1cloud.info.ssh_off')
      sleep 10
      j += 1
    end

    if j < check_num
      env[:ui].info I18n.t('vagrant_1cloud.info.ssh_on')
      break
    else
      if i < reboot_num
        # submit reboot droplet request
        result = @client.post("/server/#{@machine.id}/action", {
            :Type => 'PowerReboot'
        })

        # wait for request to complete
        env[:ui].info I18n.t('vagrant_1cloud.info.reloading')
        @client.wait_for_event(env, @machine.id, result['body']['ID'])

        i += 1
      else
        raise 'No ssh connection'
      end
    end
  end
end